[英]Plot multi-level headers dataframe with Matplotlib
我已经用 Pandas 阅读了一个 excel 文件,如下所示,我怎么能用 Matplotlib 正确地绘制它?
顺便说一句,当我read_clipboard()
这种格式的数据时,它会生成ParserError: Expected 4 fields in line 3, saw 5. Error could possibly be due to quotes being ignored when a multi-char delimiter is used.
手动修改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("")
或者您可以通过tuple
s 选择 Multiindex 值:
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("")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.