【问题标题】:Specify bar colors in simple pandas/matplotlib "barh" plot with one column在简单的 pandas/matplotlib “barh”图中用一列指定条形颜色
【发布时间】:2021-07-14 23:32:13
【问题描述】:

我有一个来自 pandas DataFrame 的条形图,其中有一列:

import pandas as pd
import matplotlib.pyplot as plt


columns = ["Foo"]
data = [50, 201, 279]
index=["Item 1", "Item 2", "Item 3"]
df = pd.DataFrame(data=data, index=index, columns=columns)

如下所示:

        Foo
Item 1   50
Item 2  201
Item 3  279

如果我使用 pandas 绘图界面绘制它:

ax = df.plot(kind="barh", color="#00576B", rot=0, legend=False, align='center', width=0.5)
ax.set_title("My title")
ax.set_ylabel("")
ax.set_xlabel("My label in foo")
ax.grid(True)
ax.set_axisbelow(True)
plt.show()

这会产生以下情节:

现在如何在不更改 DataFrame 结构或更改为 matplotlib 界面的情况下使用 pandas 绘图界面更改单个条形的颜色?

注意:我知道使用colors=["color1", "color2", ..] 传递颜色在将DataFrames 索引转换为here 描述的列时有效,但这会破坏绘图布局,例如条之间的空间。所以我正在寻找使用的直接解决方案 pandas的绘图界面和更少的代码。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    这可能不是最优雅的方式,但您始终可以循环遍历 matplotlib 补丁并单独更改它们的颜色:

    ax = df.plot(kind="barh", color="#00576B", rot=0, legend=False, align='center', width=0.5)
    ax.set_title("My title")
    ax.set_ylabel("")
    ax.set_xlabel("My label in foo")
    ax.grid(True)
    ax.set_axisbelow(True)
    # loop over patches (bars) and set colors individually
    for color, bar in zip(['red','blue','green'], ax.patches):
        bar.set_color(color)
    plt.show()
    

    输出:

    【讨论】:

    • 这对我来说绝对足够了。非常感谢:-)
    猜你喜欢
    • 2014-10-30
    • 2016-10-28
    • 2019-06-11
    • 2015-01-03
    • 2013-12-24
    • 1970-01-01
    • 2012-08-09
    • 1970-01-01
    • 2016-11-15
    相关资源
    最近更新 更多