python - 使用 Matplotlib 绘制多级标题数据框

标签 python pandas dataframe matplotlib

我用 Pandas 读取了如下的 excel 文件,如何用 Matplotlib 正确绘制它?

顺便说一句,当我 read_clipboard() 这种格式的数据时,它会生成 ParserError: Expected 4 fields in line 3, saw 5. 错误可能是由于在使用多字符分隔符。

enter image description here

手动将Excel文件修改为以下格式后:

    date  A_ratio  A_price  B_ratio  B_price
0   2007    12.00     8.90     3.04     6.35
1   2008    13.00     8.78     4.04     6.25
2   2009    14.00     9.08     5.04     6.50
3   2010    14.71     9.21     1.38     6.60
4   2011    15.71     9.22     2.38     6.66
5   2012    16.71     9.27     3.38     6.66
6   2013    16.09     9.56     1.38     6.85
7   2014    17.09     9.71     2.38     6.94
8   2015    18.09     9.31     3.38     6.65
9   2016    19.09     9.88     4.38     6.95
10  2017    20.09     9.76     5.38     6.88

我已经通过以下代码绘制了它,它有效,但我不想更改它,因为我的原始数据非常大:

df = df.set_index('date')
plt.figure(figsize=(10, 10))
cols = ['A_ratio', 'A_price', 'B_ratio', 'B_price']
df[cols].plot(kind='bar')
plt.xticks(rotation=45)
plt.xlabel("")

输出: enter image description here

请帮助我,谢谢。

最佳答案

我认为您可以将 mapjoin 一起使用来压平 MultiIndex:

df = df.set_index('date')
df.columns = df.columns.map('_'.join)

plt.figure(figsize=(10, 10))
cols = ['A_ratio', 'A_price', 'B_ratio', 'B_price']
df[cols].plot(kind='bar')
plt.xticks(rotation=45)
plt.xlabel("")

或者您可以通过元组选择多索引值:

df = df.set_index('date')

plt.figure(figsize=(10, 10))
cols = [('A','ratio'), ('A','price'), ('B','ratio'),('B','price')]
df[cols].plot(kind='bar')
plt.xticks(rotation=45)
plt.xlabel("")

关于python - 使用 Matplotlib 绘制多级标题数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59787374/

相关文章:

python - Xor 加密/解密 Python 2.7.5

python - Python 和 Perl 中是否有像 Ruby 中那样的全局对象?

python - Python 中列表的比较

python - OSX 安装 Python 分发

python - 将 json 数据转换为数据框

python - Pandas:删除数据框中的重复行

python - pandas to_sql() 错误 - 超出了准备语句每个 session 20 MB 的内存限制

python - 使用 read_csv 时如何管理包含多个空格的列名

python - 使用 pandas 和 GNU Parallel 将数据并行导入 MySQL

python - Pandas 数据框之间的点划分忽略其中一个的第一列