是否可以为matplotlib bar plot的左边缘和右边缘设置不同的edgecolor?

lnvxswe2  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(505)

我想为条形图的不同边设置不同的边颜色,用matplotlib.axes.axes.bar打印。有人知道怎么做吗?例如:右边缘为黑色,但无边缘/edgecolor为上、下和左边缘。
谢谢你的帮助!

pgky5nke

pgky5nke1#

条形图的条形图为 matplotlib.patches.Rectangle 只能有一个 facecolor 只有一个 edgecolor . 如果希望某一面有另一种颜色,可以在生成的条形图中循环,并在所需的边上绘制一条单独的线。
下面的示例代码实现了用粗黑线绘制右侧。由于一条单独的线不能与矩形完美连接,因此代码也会使用与条形图相同的颜色绘制左侧和上方。

  1. from matplotlib import pyplot as plt
  2. import numpy as np
  3. fig, ax = plt.subplots()
  4. bars = ax.bar(np.arange(10), np.random.randint(2, 50, 10), color='turquoise')
  5. for bar in bars:
  6. x, y = bar.get_xy()
  7. w, h = bar.get_width(), bar.get_height()
  8. ax.plot([x, x], [y, y + h], color=bar.get_facecolor(), lw=4)
  9. ax.plot([x, x + w], [y + h, y + h], color=bar.get_facecolor(), lw=4)
  10. ax.plot([x + w, x + w], [y, y + h], color='black', lw=4)
  11. ax.margins(x=0.02)
  12. plt.show()


ps:如果这些条是以另一种方式创建的(或者使用seaborn的例子),您可以研究 containersax . ax.containers 是一个 containers ; 一 container 是一组单独的图形对象,通常是矩形。可以有多个容器,例如在堆叠条形图中。

  1. for container in ax.containers:
  2. for bar in container:
  3. if type(bar) == 'matplotlib.patches.Rectangle':
  4. x, y = bar.get_xy()
  5. w, h = bar.get_width(), bar.get_height()
  6. ax.plot([x + w, x + w], [y, y + h], color='black')
展开查看全部

相关问题