我正在尝试使用 twinx() 在 2 y 轴上绘制数据。 问题是轴上的图例 - twinx() 未显示。
用于预期结果的代码如下:
df_plot = DF02.query('Make == "Acura"')
Fig = plt.figure()
ax1 = Fig.add_axes([0, 0, 1, 1])
ax2 = ax1.twinx()
# Drawing a line plot
sns.lineplot(data = df_plot,
x = 'Year',
y = 'highway MPG',
hue = 'Model',
palette = 'rocket',
style = 'Model',
markers = True,
dashes = False,
ax = ax1)
# Drawing line plot on ax2 using matplotlib
ax2.plot(df_plot['Year'],
df_plot['avg highway MPG'],
marker = '*',
label = 'avg highway MPG')
# Set x-axis and y-axis ticks
xticks = np.arange(1990, 2021, 2)
ax1.set_xticks(xticks)
yticks = np.arange(10, 41, 2)
ax1.set_yticks(yticks)
ax2.set_yticks(yticks)
ax2.axes.get_yaxis().set_visible(False)
# Change name of plot title
ax1.set_title("Line Plot in Seaborn", fontdict = {'weight': 'bold'})
# Change x and y axis titles
ax1.set_xlabel('Year')
ax1.set_ylabel('Highway Fuel Economy [MPG]')
# Placing the legend
ax1.legend(title = "Vehicle Model\n", loc = 'center right', bbox_to_anchor = (1.3, 0.5))
ax2.legend(title = 'Legend', loc = 'upper right', bbox_to_anchor = (1, 1))
# Enabling the grid
ax1.grid(ls = '--', color = 'lightgrey')
实际结果使用的代码如下:
df_plot = DF02.query('Make == "Acura"')
Fig = plt.figure()
ax1 = Fig.add_axes([0, 0, 1, 1])
ax2 = ax1.twinx()
# Drawing a line plot
sns.lineplot(data = df_plot,
x = 'Year',
y = 'highway MPG',
hue = 'Model',
palette = 'rocket',
style = 'Model',
markers = True,
dashes = False,
ax = ax1)
sns.lineplot(data = df_plot,
x = 'Year',
y = 'avg highway MPG',
ax = ax2)
# Set x-axis and y-axis ticks
xticks = np.arange(1990, 2021, 2)
ax1.set_xticks(xticks)
yticks = np.arange(10, 41, 2)
ax1.set_yticks(yticks)
ax2.set_yticks(yticks)
ax2.axes.get_yaxis().set_visible(False)
# Change name of plot title
ax1.set_title("Line Plot in Seaborn", fontdict = {'weight': 'bold'})
# Change x and y axis titles
ax1.set_xlabel('Year')
ax1.set_ylabel('Highway Fuel Economy [MPG]')
# Placing the legend
ax1.legend(title = "Vehicle Model\n", loc = 'center right', bbox_to_anchor = (1.3, 0.5))
ax2.legend(loc = 'upper right', bbox_to_anchor = (1, 1))
# Enabling the grid
ax1.grid(ls = '--', color = 'lightgrey')
任何人都可以建议如何通过在轴 ax1 和 ax2 上使用 seaborn 来获得与预期结果类似的结果吗?
调用
sns.lineplot(data=df_plot, x='Year', y='avg highway MPG', ax=ax2)
不会生成图例条目,因为只绘制了一条线(没有“hue”参数)。 您可以添加一个标签:sns.lineplot(..., label='avg highway MPG')
来告诉matplotlib您想在图例中看到什么。
要更改图例参数,
ax2.legend(...)
通常不适用于使用seaborn创建的绘图。相反,在seaborn中,建议sns.move_legend(...)
更改标题和其他图例属性。
这是一个最小的例子,首先模仿原始代码:
import matplotlib.pyplot as plt
import seaborn as sns
mpg = sns.load_dataset('mpg')
ax2 = sns.lineplot(mpg, x='model_year', y='mpg')
ax2.legend(loc='upper right', bbox_to_anchor=(1, 1))
这会发出警告
No artists with labels found to put in legend.
并创建一个空图例:
添加标签会创建图例:
import matplotlib.pyplot as plt
import seaborn as sns
mpg = sns.load_dataset('mpg')
ax2 = sns.lineplot(mpg, x='model_year', y='mpg', label='miles per gallon')
plt.show()
您可以通过
sns.move_legend(ax2, loc='upper right')
移动图例和/或更改其他属性。