【问题标题】:Simple python question about data visualization关于数据可视化的简单python问题
【发布时间】:2021-09-26 00:43:26
【问题描述】:

我想要一个显示 2000 年阿尔巴尼亚所有疾病数量的条形图。

我试过这个,但我无法得到我想要的。

fig, ax = plt.subplots()
ax.bar(df[country['Albania']], df['2000'])
plt.xlabel('Fruit', fontsize=17, fontname='Times New Roman')
plt.ylabel('Spent', fontsize=17, fontname='Times New Roman')
plt.title('Share of diseases in Albania in 2000 ', fontsize=17, fontname="Times New Roman")

plt.show()

【问题讨论】:

  • 您需要将数据框过滤为仅 'Albania' '2000' 行。看起来那些是多索引。您还标记了seaborn,但您似乎正在使用matplotlib 进行绘图。
  • 可以使用 seaborn 或 matplotlib 完成。我没有理解你关于多索引的观点。

标签: python pandas plot seaborn visualization


【解决方案1】:

让我们先建立一个虚拟的例子:

import numpy as np
import pandas as pd
import itertools

np.random.seed(0)
df = pd.DataFrame({('Country_%s' % c, y): {'disease_%d' % (i+1): np.random.randint(100)
                                           for i in range(4)}
                    for c,y in itertools.product(list('ABCD'), range(1998,2002))
                   }).T
df.index.names = ('country', 'year')
                disease_1  disease_2  disease_3  disease_4
country   year                                            
Country_A 1998         44         47         64         67
          1999         67          9         83         21
          2000         36         87         70         88
          2001         88         12         58         65
Country_B 1998         39         87         46         88
          1999         81         37         25         77
          2000         72          9         20         80
          2001         69         79         47         64
Country_C 1998         82         99         88         49
          1999         29         19         19         14
          2000         39         32         65          9
          2001         57         32         31         74
Country_D 1998         23         35         75         55
          1999         28         34          0          0
          2000         36         53          5         38
          2001         17         79          4         42

然后,您可以为每个国家和年份设置一个多索引行的子集

df.loc[('Country_B', 2000)]

输出:

disease_1    72
disease_2     9
disease_3    20
disease_4    80
Name: (Country_B, 2000), dtype: int64

和绘图(这里使用 pandas+matplotlib):

ax = df.loc[('Country_B', 2000)].plot.bar()
ax.set_ylabel('number of cases')

【讨论】:

  • 非常感谢。你能帮忙在一个情节中显示 2 年吗?
  • 试试df.query('country == "Country_B" & year in [2000, 2001]').plot.bar()和df.query('country == "Country_B" & year in [2000, 2001]').T.plot.bar()
猜你喜欢
  • 2018-07-27
  • 1970-01-01
  • 2022-10-18
  • 1970-01-01
  • 2021-11-02
  • 1970-01-01
  • 1970-01-01
  • 2012-09-19
  • 2019-09-15
相关资源
最近更新 更多