带有第二个 y 轴的 Seaborn 图

CHA*_*DTO 6 python matplotlib seaborn

我想知道如何用两个 y 轴绘制一个图,以便我的图看起来像这样: 在此处输入图片说明

通过添加另一个 y 轴来实现更像这样的东西: 在此处输入图片说明

我只使用我的情节中的这行代码,以便从我的数据框中获取前 10 个 EngineVersions:

sns.countplot(x='EngineVersion', data=train, order=train.EngineVersion.value_counts().iloc[:10].index);
Run Code Online (Sandbox Code Playgroud)

小智 14

@gdubs如果你想用 Seaborn 的库来做到这一点,这个代码设置对我有用。您无需在 matplotlib 中的绘图函数“外部”设置 ax 赋值,而是在 Seaborn 中的绘图函数“内部”进行设置,其中ax是存储绘图的变量。

import seaborn as sns # Calls in seaborn

# These lines generate the data to be plotted
x = [1,2,3,4,5]
y = [1000,2000,500,8000,3000]
y1 = [1050,3000,2000,4000,6000]

fig, ax1 = plt.subplots() # initializes figure and plots

ax2 = ax1.twinx() # applies twinx to ax2, which is the second y axis. 

sns.barplot(x = x, y = y, ax = ax1, color = 'blue') # plots the first set of data, and sets it to ax1. 
sns.lineplot(x = x, y = y1, marker = 'o', color = 'red', ax = ax2) # plots the second set, and sets to ax2. 

# these lines add the annotations for the plot. 
ax1.set_xlabel('X data')
ax1.set_ylabel('Counts', color='g')
ax2.set_ylabel('Detection Rates', color='b')

plt.show(); # shows the plot. 
Run Code Online (Sandbox Code Playgroud)

输出: Seaborn 输出示例


web*_*Dev 11

我认为您正在寻找类似的东西:

import matplotlib.pyplot as plt
x = [1,2,3,4,5]
y = [1000,2000,500,8000,3000]
y1 = [1050,3000,2000,4000,6000]

fig, ax1 = plt.subplots()

ax2 = ax1.twinx()
ax1.bar(x, y)
ax2.plot(x, y1, 'o-', color="red" )

ax1.set_xlabel('X data')
ax1.set_ylabel('Counts', color='g')
ax2.set_ylabel('Detection Rates', color='b')

plt.show()
Run Code Online (Sandbox Code Playgroud)

输出:

在此处输入图片说明

  • 对于 @gdubs 来说可能为时已晚,但以防万一有人感兴趣 - 您可以像往常一样使用 Seaborn (sns) 绘制图表,只需创建新的 ax (ax2 = ax1.twinx()),然后转发适当的 Axes 对象使用 'ax' 参数连接到 Seaborn 函数,例如: ax1.bar(x, y) => sns.barplot(x=x, y=y, ax=ax1) ax2.plot(x, y1, 'o -', color="red" ) => sns.lineplot(x=x, y=y1, color="red", ax=ax2) (6认同)
  • 你如何用 sns 做到这一点? (2认同)