我可以将边缘设置作为一个应用于所有堆叠的条形吗?
这是一个示例:
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)
我想要绿色边缘围绕在整个条上,而又不会在堆叠的矩形之间折断,有什么主意吗?
答案 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)
)
答案 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)
要仅在一些条形周围绘制一个矩形,请将总和设置为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)