熊猫堆积条形图-更改堆积条的edgecolor

时间:2020-07-14 12:55:50

标签: python pandas matplotlib bar-chart

我可以将边缘设置作为一个应用于所有堆叠的条形吗?

这是一个示例:

df = pd.DataFrame([[2,5,7,11], [4,8,11,45]]).T
ax = df.plot.bar(stacked=True)
ax.containers[0][2].set_edgecolor('green')
ax.containers[0][2].set_linewidth(5)
ax.containers[1][2].set_edgecolor('green')
ax.containers[1][2].set_linewidth(5)

这给出: enter image description here

我想要绿色边缘围绕在整个条上,而又不会在堆叠的矩形之间折断,有什么主意吗?

2 个答案:

答案 0 :(得分:2)

我不确定您是否可以指定不绘制每个矩形的边缘之一。因此,一个想法是独立绘制Rectangle并从ax.containers访问位置,高度和宽度。

from matplotlib.patches import Rectangle
df = pd.DataFrame([[2,5,7,11], [4,8,11,45]]).T
ax = df.plot.bar(stacked=True)
ax.add_patch(Rectangle(xy=ax.containers[0][2].get_xy(), 
                       width=ax.containers[0][2].get_width(),
                       height=ax.containers[0][2].get_height() 
                              +ax.containers[1][2].get_height(), 
                       fc='none', ec='green', linewidth=5)
            )

enter image description here

答案 1 :(得分:2)

您可以分两步进行绘制:首先是堆叠的条,然后是相加的条。

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

df = pd.DataFrame([[2, 5, 7, 11], [4, 8, 11, 45]]).T
ax = df.plot.bar(stacked=True)
ax = df.sum(axis=1).plot.bar(facecolor='none', edgecolor='green', lw=5, ax=ax)

example plot

要仅在一些条形周围绘制一个矩形,请将总和设置为NaN,除了要突出显示的条形:

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

df = pd.DataFrame([[2, 5, 7, 11], [4, 8, 11, 45]]).T
dfs = df.sum(axis=1)
dfs.iloc[df.index != 2] = np.nan

ax = df.plot.bar(stacked=True)
ax = dfs.plot.bar(facecolor='none', edgecolor='green', lw=5, ax=ax)

only a rectangle around bar 2