python - Matplotlib 堆叠条形图,具有类似于 pgfplots 的单独边缘颜色

标签 python matplotlib

我有一些堆叠的条形图,可能看起来像这样

enter image description here

但我真的很喜欢跟随其余颜色的边缘颜色,例如像 pgfplots enter image description here

这在 Matplotlib 中可能(在合理范围内)吗?

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

test1 = np.array([51, 13.8, 15.5, np.NaN])
test2 = np.array([40.3, 30.4, 13.8, 15.5])

df = pd.DataFrame(dict(test1 = test1,
                       test2 = test2),
                  columns = ["test1","test2"]).T

ax = df.plot.barh(stacked = True, cmap = "coolwarm", edgecolor = "black", lw = 1, width = 0.8, figsize = (6,4))
plt.show()

最佳答案

首先,条形图的边缘是黑色的,因为您在调用 df.plot.barh 时设置了 edgecolor = "black"。删除它意味着不会有边缘颜色。您需要将每个条形的边缘颜色设置为条形的面颜色

您可以通过迭代矩形补丁(使用 ax.patches 获得)并使用 get_facecolor() 将边缘颜色设置为面部颜色来完成此操作。和 set_edgecolor() .

test1 = np.array([51, 13.8, 15.5, np.NaN])
test2 = np.array([40.3, 30.4, 13.8, 15.5])

df = pd.DataFrame(dict(test1 = test1,
                       test2 = test2),
                  columns = ["test1","test2"]).T

ax = df.plot.barh(stacked = True, cmap = "coolwarm", lw = 1.5, width = 0.8, figsize = (6,4))

for rect in ax.patches:
    facecolor = list(rect.get_facecolor())
    rect.set_edgecolor(facecolor)

    facecolor[-1] = 0.5  # reduce alpha value of facecolor, but not of edgecolor
    rect.set_facecolor(facecolor)

plt.show()

这给出:

enter image description here

关于python - Matplotlib 堆叠条形图,具有类似于 pgfplots 的单独边缘颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49656414/

相关文章:

python - 超过 1000 个主机的 pysnmp 扭曲客户端中的未处理错误

python - 如何使用 python re.findall 过滤掉这种特殊模式?

python - 导入 Pybind11/C++ 编译模块不起作用

python - 返回方程最接近于零的输入数字

python - Matplotlib Legend for Scatter 自定义颜色

python - 创建复杂的条件列(几何平均数)Python

python - 使用 Matplotlib 自定义基于时间序列的数据的 x Axis

python - python中的mpl_finance模块导入错误

python - 如何使用pip和自制软件安装SciPy Stack?

python - 更改 matplotlib 中的 latex 数学字体样式