Skip to main content
 首页 » 编程设计

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

2024年09月07日7lori

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

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

在 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() 

给出: