简体   繁体   English

pandas 堆叠条 plot - 改变堆叠条的边缘颜色

[英]pandas stacked bar plot - change the edgecolor of stacked bar

Can I get the edge settings to apply on all stacked bar as one?我可以将边缘设置应用到所有堆叠条上吗?

here is an example:这是一个例子:

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)

this gives:这给出了: 在此处输入图像描述

what I want is the green edge to be around the whole bar without breaking between the stacked rectangles, any ideas?我想要的是绿色边缘围绕整个条形而不会在堆叠的矩形之间中断,有什么想法吗?

I'm not sure you can specify to not plot one of the edges for each of the Rectangle.我不确定您是否可以指定不是 plot 每个矩形的边缘之一。 So one idea is to plot a Rectangle independently and access the positions, height and width from the ax.containers .所以一个想法是 plot 一个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)
            )

在此处输入图像描述

You can draw it in two steps: first the stacked bars and then the summed bars.您可以分两步绘制它:首先是堆叠的条形图,然后是汇总的条形图。

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)

示例图

To only draw a rectangle around some bars, set the sum to NaN except for the bars to be highlighted:要仅在某些条形周围绘制一个矩形,请将总和设置为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)

仅围绕条 2 的矩形

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM