Matplotlib具有类似于pgfplots的单个边颜色的堆叠条形图

2024-10-05 10:40:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

Tags: importnumpydfmatplotlib颜色asnpplt
1条回答
网友
1楼 · 发布于 2024-10-05 10:40:40

首先,条的边缘是黑色的,因为您在对df.plot.barh的调用中设置了edgecolor = "black"。删除这意味着将没有edgecolor。您需要将每个条的edgecolor设置为条的facecolor

您可以通过遍历矩形面片(使用ax.patches获得)并使用^{}^{}将edgecolor设置为facecolor来实现

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

相关问题 更多 >

    热门问题