我有一些堆叠的条形图,可能看起来像这样
但我真的很喜欢跟随其余颜色的边缘颜色,例如像 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()
这给出:
关于python - Matplotlib 堆叠条形图,具有类似于 pgfplots 的单独边缘颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49656414/