第二y轴的Seaborn图

时间:2019-04-12 15:00:10

标签: python matplotlib seaborn

我想知道如何绘制带有两个y轴的图,这样我的图看起来像这样:enter image description here

通过添加另一个y轴,使

更像这样: enter image description here

我仅使用我的绘图中的这一行代码,以便从数据框中获取前10个EngineVersions:

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

2 个答案:

答案 0 :(得分:3)

@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. 

输出: Seaborn output example

答案 1 :(得分:1)

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

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()

输出:

enter image description here