Python 将图例添加到 Seaborn 点图
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42767489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add Legend to Seaborn point plot
提问by Spandan Brahmbhatt
I am plotting multiple dataframes as point plot using seaborn
. Also I am plotting all the dataframes on the same axis.
我正在使用seaborn
. 我也在同一轴上绘制所有数据框。
How would I add legend to the plot ?
我将如何在情节中添加图例?
My code takes each of the dataframe and plots it one after another on the same figure.
我的代码获取每个数据框并在同一个图形上一个接一个地绘制它。
Each dataframe has same columns
每个数据框都有相同的列
date count
2017-01-01 35
2017-01-02 43
2017-01-03 12
2017-01-04 27
My code :
我的代码:
f, ax = plt.subplots(1, 1, figsize=figsize)
x_col='date'
y_col = 'count'
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df_1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df_2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df_3,color='red')
This plots 3 lines on the same plot. However the legend is missing. The documentationdoes not accept label
argument .
这在同一个图上绘制了 3 条线。然而,传说不见了。该文档不接受label
参数。
One workaround that worked was creating a new dataframe and using hue argument
.
一种有效的解决方法是创建一个新的数据框并使用hue argument
.
df_1['region'] = 'A'
df_2['region'] = 'B'
df_3['region'] = 'C'
df = pd.concat([df_1,df_2,df_3])
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df,hue='region')
But I would like to know if there is a way to create a legend for the code that first adds sequentially point plot to the figure and then add a legend.
但我想知道是否有一种方法可以为代码创建图例,该代码首先向图中添加顺序点图,然后添加图例。
Sample output :
示例输出:
回答by ImportanceOfBeingErnest
I would suggest not to use seaborn pointplot
for plotting. This makes things unnecessarily complicated.
Instead use matplotlib plot_date
. This allows to set labels to the plots and have them automatically put into a legend with ax.legend()
.
我建议不要使用 seabornpointplot
进行绘图。这使事情变得不必要地复杂。
而是使用 matplotlib plot_date
。这允许为绘图设置标签,并让它们自动放入带有ax.legend()
.
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
date = pd.date_range("2017-03", freq="M", periods=15)
count = np.random.rand(15,4)
df1 = pd.DataFrame({"date":date, "count" : count[:,0]})
df2 = pd.DataFrame({"date":date, "count" : count[:,1]+0.7})
df3 = pd.DataFrame({"date":date, "count" : count[:,2]+2})
f, ax = plt.subplots(1, 1)
x_col='date'
y_col = 'count'
ax.plot_date(df1.date, df1["count"], color="blue", label="A", linestyle="-")
ax.plot_date(df2.date, df2["count"], color="red", label="B", linestyle="-")
ax.plot_date(df3.date, df3["count"], color="green", label="C", linestyle="-")
ax.legend()
plt.gcf().autofmt_xdate()
plt.show()
如果仍然有兴趣获得点图的图例,这里有一种方法:
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df1,color='blue')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df2,color='green')
sns.pointplot(ax=ax,x=x_col,y=y_col,data=df3,color='red')
ax.legend(handles=ax.lines[::len(df1)+1], labels=["A","B","C"])
ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
plt.gcf().autofmt_xdate()
plt.show()
回答by Adam B
Old question, but there's an easier way.
老问题,但有一个更简单的方法。
sns.pointplot(x=x_col,y=y_col,data=df_1,color='blue')
sns.pointplot(x=x_col,y=y_col,data=df_2,color='green')
sns.pointplot(x=x_col,y=y_col,data=df_3,color='red')
plt.legend(labels=['legendEntry1', 'legendEntry2', 'legendEntry3'])
This lets you add the plots sequentially, and not have to worry about any of the matplotlib crap besides defining the legend items.
这使您可以按顺序添加图,而不必担心除了定义图例项之外的任何 matplotlib 废话。
回答by PSub
I tried using Adam B's answer, however, it didn't work for me. Instead, I found the following workaround for adding legends to pointplots.
我尝试使用 Adam B 的答案,但是,它对我不起作用。相反,我找到了以下解决方法来向点图添加图例。
import matplotlib.patches as mpatches
red_patch = mpatches.Patch(color='#bb3f3f', label='Label1')
black_patch = mpatches.Patch(color='#000000', label='Label2')
In the pointplots, the color can be specified as mentioned in previous answers. Once these patches corresponding to the different plots are set up,
在点图中,可以按照前面的答案中所述指定颜色。一旦设置了对应于不同图的这些补丁,
plt.legend(handles=[red_patch, black_patch])
And the legend ought to appear in the pointplot.
并且图例应该出现在点图中。