我有根据 pandas 数据框计算出的直方图。
我想根据 x 轴值更改颜色。
例如:
If the value is = 0 the color should be green
If the value is > 0 the color should be red
If the value is < 0 the color should be yellow
我只关心 x 轴。酒吧的高度对我来说并不重要。所有其他解决方案均针对 y 轴。
对于每个条形补丁ax.containers[0]
, use set_color https://matplotlib.org/stable/api/_as_gen/matplotlib.patches.Patch.html#matplotlib.patches.Patch.set_color基于x
位置:
-
get_x https://matplotlib.org/stable/api/_as_gen/matplotlib.patches.Rectangle.html#matplotlib.patches.Rectangle.get_x返回左边缘,因此通过添加一半来获得中点get_width https://matplotlib.org/stable/api/_as_gen/matplotlib.patches.Rectangle.html#matplotlib.patches.Rectangle.get_width
-
x
可能不会exactly0,因此使用一些缓冲区进行测试(本例中为 0.2)
自从你在评论中询问熊猫 https://stackoverflow.com/questions/70202374/how-to-change-histogram-color-based-on-x-axis-in-matplotlib#comment124102024_70202516,这个例子使用DataFrame.plot.hist https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.hist.html,但您可以使用任何基于 matplotlib 的直方图/条形图来执行此操作:
df = pd.DataFrame({'A': np.random.default_rng(222).uniform(-1, 1, 40)})
ax = df.plot.hist()
for bar in ax.containers[0]:
# get x midpoint of bar
x = bar.get_x() + 0.5 * bar.get_width()
# set bar color based on x
if x < -0.2:
bar.set_color('orange')
elif x > 0.2:
bar.set_color('red')
else:
bar.set_color('green')
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)