[英]Python Pandas MultiIndex Plot has incorrectly colored legend
This seems to be a genereal and repeated (and unsolved) issue when trying to plot information from a Python Pandas MultiIndex.在尝试从 Python Pandas MultiIndex 绘制信息时,这似乎是一个普遍且重复(且未解决)的问题。
The plotting code:绘图代码:
df.unstack(0).plot(x='SHIFT', y='INFORMATION_SURPLUS_PCT')
will render the following graph:将呈现以下图形:
Unfortunately the color of the legend lines do not match the lines on the graph, I've also tried the following code to supply a legend but this still doesn't match up:不幸的是,图例线的颜色与图表上的线不匹配,我还尝试了以下代码来提供图例,但这仍然不匹配:
df.unstack(0).plot(x='SHIFT', y='INFORMATION_SURPLUS_PCT', legend=df.index.levels)
Example df:示例 df:
INFORMATION_SURPLUS_DIFF INFORMATION_SURPLUS_PCT \
SYMBOL
LBTYB 0 0.000000 0.000000
1 0.015046 11.206891
2 0.042249 31.468118
3 0.005421 4.037495
4 -0.005569 0.000000
5 -0.069742 0.000000
6 0.036281 27.022972
7 0.072626 54.093432
8 -0.026966 0.000000
9 -0.048241 0.000000
10 0.145121 108.088780
MNST 0 0.000000 0.000000
1 0.062962 0.000000
2 0.029280 0.000000
3 0.056574 63.569509
4 0.088341 99.265331
5 0.052083 0.000000
6 0.041253 46.353665
7 0.058658 65.911282
8 0.080748 90.732985
9 0.031419 0.000000
10 0.055326 62.167628
MUTUAL_INFORMATION SHIFT
SYMBOL
LBTYB 0 0.134261 0
1 0.149307 -1
2 0.176510 -2
3 0.139681 -3
4 0.128692 -4
5 0.064518 -5
6 0.170542 -6
7 0.206887 -7
8 0.107294 -8
9 0.086020 -9
10 0.279381 -10
MNST 0 0.088995 0
1 0.151957 -1
2 0.118276 -2
3 0.145569 -3
4 0.177337 -4
5 0.141078 -5
6 0.130248 -6
7 0.147653 -7
8 0.169743 -8
9 0.120414 -9
10 0.144322 -10
This code snippet will work, it involves grouping the MultiIndex and plotting to the same figure in a loop - Open for improvements:此代码片段将起作用,它涉及对 MultiIndex 进行分组并在循环中绘制到同一图 - 打开以进行改进:
grouped = df.groupby(level=0)
ax = plt.figure()
first = True
for i, group in grouped:
print i
if first:
ax = group.plot(x='SHIFT', y='INFORMATION_SURPLUS_PCT', label=str(i))
first = False
else:
group.plot(ax=ax, x='SHIFT', y='INFORMATION_SURPLUS_PCT', label=str(i))
New plot image:新的情节图像:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.