[英]How to plot this type of graph (errorbar)?
I have a dataframe: 我有一个数据框:
import pandas as pd
import numpy as np
df = pd.read_csv(r'https://exploratory.io/data/kanaugust/2016-California-Election-Data-oTv4Hgd1UT/2016%20California%20Election%20Data.csv')
df['cluster'] = [3, 3, 1, 2, 1, 1, 3, 1, 1, 2, 1, 3, 2, 1, 1, 1, 2, 1, 3, 1, 3, 1, 3, 2, 1, 2, 3, 3, 2, 2, 1, 1, 2, 2, 2, 2, 2, 3, 2, 2, 3, 3, 3, 3, 1, 1, 1, 2, 3, 2, 1, 1, 1, 1, 1, 2, 3, 1]
df = df.drop(columns=['COUNTY_NAME', 'PARTY_NAME']).groupby('cluster').agg(['mean', 'std'])
df
I would like to make graph of it, like this one: 我想制作一张图,像这样:
For each cluster every line is drawn as line that connects three dots. 对于每个簇,将每条线绘制为连接三个点的线。 In the middle is column mean, lower dot is mean - std, and upper mean + std.
中间是列均值,下点是均值-std,上限是均值+ std。 For example for Ban on Single-use Plastic Bags and cluster 3, lower dot is 0.647902 - 0.065703, dot in the middle is 0.647902, and upper dot is 0.647902 + 0.065703.
例如,对于“一次性塑料袋禁令”和第3组,下点是0.647902-0.065703,中间的点是0.647902,上面的点是0.647902 + 0.065703。
On each x position all three clusters should be drawn, each in different color. 在每个x位置应绘制所有三个簇,每个簇的颜色不同。
matplotlib errorbar could be good for that purpose, but I don't know how to use it to produce the graph as I shown above. matplotlib错误栏可能会达到该目的,但是我不知道如何使用它来生成上面显示的图形。 Maybe seaborn is good as well?
也许seaborn也很好?
How to draw this kind of graph? 如何绘制这种图形?
One way to do so with errorbar : 使用errorbar的一种方法:
df = df.drop(columns=['COUNTY_NAME', 'PARTY_NAME']).groupby('cluster').agg(['mean', 'std'])
# change categories to index
new_df = df.T.unstack()
fig, ax = plt.subplots(1,1, figsize=(16,10))
for i in range(1,4):
ax.errorbar(range(len(new_df)), new_df[new_df.columns[2*i-2]],
yerr=new_df[new_df.columns[2*i-1]], fmt='x',
label=f'Cluster {i}')
ax.set_xticks(range(len(new_df)))
ax.set_xticklabels(new_df.index)
ax.legend()
plt.show()
Output is not perfect, but I leave the detail to you: 输出并不完美,但我将细节留给您:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.