我有一个数据框架:
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

我想把它画成图表,就像这个:

对于每个簇,每条线都被绘制为连接三个点的线。中间是列平均值,下点是mean - std,上部是mean + std。例如,禁止使用一次性塑料袋和集群3,下网点为0.647902 - 0.065703,中间网点为0.647902,上网点为0.647902 + 0.065703。
在每个x位置上,应该绘制所有三个簇,每个簇都有不同的颜色。
matplotlib errorbar可以很好地实现这个目的,但我不知道如何使用它来生成上面所示的图形。也许海运也不错?
如何绘制这样的图表?
发布于 2019-04-24 04:48:38
使用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()输出并不完美,但我将细节留给您:

https://stackoverflow.com/questions/55817902
复制相似问题