【问题标题】:How to plot this type of graph (errorbar)?如何绘制这种类型的图表(误差线)?
【发布时间】:2019-04-23 19:09:15
【问题描述】:

我有一个数据框:

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

我想制作它的图表,像这样:

对于每个集群,每条线都绘制为连接三个点的线。 中间是列均值,下点是均值 - 标准,上均值 + 标准。 例如禁止一次性塑料袋和集群 3,下点为 0.647902 - 0.065703,中间点为 0.647902,上点为 0.647902 + 0.065703。

应该在每个 x 位置绘制所有三个簇,每个簇都用不同的颜色。

matplotlib 错误栏可能适用于此目的,但我不知道如何使用它来生成如上所示的图表。 也许seaborn也不错?

这种图形怎么画?

【问题讨论】:

  • matplotlib 拥有我见过的最好的文档资源之一。例如,快速浏览一下这个matplotlib.org/gallery/statistics/…,你可以试试。
  • 我仍然不知道如何为每个多索引列绘制它。
  • 如果你的列不是多索引的,你知道如何绘制它吗?

标签: python pandas matplotlib seaborn


【解决方案1】:

使用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()

输出并不完美,但我把细节留给你:

【讨论】:

  • 就是这样。非常感谢。
猜你喜欢
  • 1970-01-01
  • 2021-12-19
  • 2013-03-15
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
相关资源
最近更新 更多