将图例添加到Seaborn点图 [英] Add Legend to Seaborn point plot
问题描述
我正在使用seaborn
将多个数据框绘制为点图.另外,我正在在同一轴上绘制所有数据框.
I am plotting multiple dataframes as point plot using seaborn
. Also I am plotting all the dataframes on the same axis.
如何在图例中添加图例?
我的代码获取每个数据框,并将其一个接一个地绘制在同一张图上.
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
我的代码:
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')
这将在同一图上绘制3条线.但是,传说不见了. 文档不接受label
参数.
This plots 3 lines on the same plot. However the legend is missing. The documentation does not accept label
argument .
一种可行的解决方法是创建一个新的数据框并使用hue argument
.
One workaround that worked was creating a new dataframe and using 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.
样本输出:
推荐答案
我建议不要使用seaborn pointplot
进行绘图.这使事情变得不必要地复杂.
而是使用matplotlib plot_date
.这样就可以在图上设置标签,并使用ax.legend()
将它们自动放入图例中.
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()
.
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()
如果仍然对获取点状图例感兴趣,请尝试以下方法:
In case one is still interested in obtaining the legend for pointplots, here a way to go:
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()
这篇关于将图例添加到Seaborn点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!