【问题标题】:How to set colors of specific bars in matplotlib object oriented way?如何以 matplotlib 面向对象的方式设置特定条的颜色?
【发布时间】:2020-12-24 20:43:21
【问题描述】:

如果您使用的是面向对象的方法,目前没有简单的方法可以在 matplotlib 中为特定条形设置特定颜色

这引出了我的第二个问题,即 在 matplotlib 中绘制的最佳方法是什么(pyplot 一或 oop 一)?

我发现的一个 hack:

  heights = x
  labels = y

  colors = ["dimgrey" for x in labels]
  if np.isin(true_val, labels):
    index = np.argmax(labels == true_val)
    colors[index] = "green"

  ax[3].bar(labels, heights, color=colors)

Pyplot方式:

barlist=plt.bar([1,2,3,4], [1,2,3,4])
barlist[0].set_color('r')

类似问题:

【问题讨论】:

    标签: python matplotlib data-visualization jupyter


    【解决方案1】:

    将从ax[1].bar(labels, heights, color="dimgrey") 返回的barcontainer 分配给barlist 并使用barlist 操作颜色。

    heights = x
    labels = y
    
    barlist = ax[1].bar(labels, heights, color="dimgrey")
    
    barlist[0].set_color('green')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-02
      • 1970-01-01
      • 2015-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-14
      相关资源
      最近更新 更多