python - Pandas + Matplotlib,让条形图中的一种颜色脱颖而出

标签 python matplotlib pandas

我有一个不同颜色的条形图。我想让一个条形图以更亮的颜色脱颖而出,而其他条形图则褪色。我的猜测是使用条上的关键字 alpha 来淡化它们,但我不知道如何使它们保持原始颜色(= 不使用 alpha 关键字淡化)。 我需要这方面的帮助 这是我的代码:

from matplotlib import pyplot as plt
from itertools import cycle, islice
import pandas as pd, numpy as np 



ds2=ds[['Factors', 'contribution']]
ds3=ds2.set_index('Factors')


it = cycle(['b', 'green', 'y', 'pink','orange','cyan','darkgrey'])
my_colors=[next(it) for i in xrange(len(ds))]

figure(1, figsize=(10,8))

# Specify this list of colors as the `color` option to `plot`.
ds3.plot(kind='barh', stacked=True, color=my_colors, alpha=0.95)
plt.title('xxxxxxxxxxxxxx', fontsize = 10)

enter image description here

这是我的简单数据框 ds3

         contribution
Factors              
A            0.188137
B            0.160208
C            0.160208
D            0.151654
E            0.149489
F            0.135975
G            0.063206

最佳答案

如果您在 Matplotlib 命令中添加来自 Pandas 的数据,我认为 mgilson 的方法是最好的。但是,您也可以捕获 Pandas 返回的 axes 对象,然后遍历艺术家以修改它们。

这变得非常棘手,因为条形图没有标签(它的“_no_legend_”)作为标识符,定位特定条形图的唯一方法是在原始 DataFrame 的索引中查找它的位置。在绘图和查找之间的顺序中的任何更改(如排序)都会给出错误的结果!

import pandas as pd

df = pd.DataFrame({'contribution': [0.188137,0.160208,0.160208,0.151654,0.149489,0.135975,0.063206]}
                  ,index=['A','B','C','D','E','F','G'])

colors = ['b', 'green', 'y', 'pink','orange','cyan','darkgrey']

ax = df.plot(kind='barh', color=colors, legend=False)

for bar in ax.patches:
    bar.set_facecolor('#888888')

highlight = 'D'
pos = df.index.get_loc(highlight)

ax.patches[pos].set_facecolor('#aa3333')
ax.legend()

enter image description here

因此,此示例仅对 Pandas 和 Matplotlib 如何协同工作提供了一点见解。我不建议实际使用它,建议只采用 mgnilson 的方法。

关于python - Pandas + Matplotlib,让条形图中的一种颜色脱颖而出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20394091/

相关文章:

python - 在 Tkinter 中更改 matplotlib 的导航工具栏大小

python - 您可以使用 FileZilla 部署 Flask 应用程序吗?

python - 如何在 matplotlib 小部件的嵌入式图形上使用跨度选择器?

python - 旋转点并使用 cv2.polylines 绘制

python-3.x - 对于来自 seaborn 的计数图,Matplotlib 的替代方案是什么?

python - 使用多个多索引级别删除

python - 如果存在特定模式(例如数字然后字母),如何将数据透视表应用于数据框列?

python - 绘制系列饼图

python - tkinter LabelFrame 没有附加小部件

python - Google App Engine 柔性环境中的 "Failed to import google/appengine/ext/deferred/handler.py"