我用 Pandas 读取了如下的 excel 文件,如何用 Matplotlib 正确绘制它?
顺便说一句,当我 read_clipboard()
这种格式的数据时,它会生成 ParserError: Expected 4 fields in line 3, saw 5. 错误可能是由于在使用多字符分隔符。
手动将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("")
请帮助我,谢谢。
最佳答案
我认为您可以将 map
与 join
一起使用来压平 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/