【问题标题】:How to colour all bars after a certain date in a matplotlib date bar chart如何在matplotlib日期条形图中的某个日期之后为所有条形着色
【发布时间】:2020-04-13 06:22:12
【问题描述】:

我有一个数据集,其中包含一个名为x 的列表中的datetime.datetime 对象和一个名为y 的整数列表。我像这样绘制它们:

plt.bar(x, y)
plt.show()

在给定日期之后,我将如何为所有条形着色另一种颜色?我知道我可以通过分配plt.bar(x, y) 的结果来获得条形列表,但除了制作简单的绘图之外,我从来没有搞乱过matplotlib

【问题讨论】:

标签: python matplotlib python-datetime


【解决方案1】:

您可以制作一个布尔掩码,根据日期是否大于另一个日期返回 0 或 1。然后使用这个数组来获取颜色列表。

import matplotlib.pyplot as plt
import datetime
import numpy as np

base = datetime.datetime.today()

x = [base - datetime.timedelta(days=x) for x in range(10)]
y = np.random.randint(0, 10, 10)

greater = np.greater(x, datetime.datetime(2020, 4, 7)).astype(int)
colors = np.array(['red', 'green'])

plt.bar(x, y, color=colors[greater])

greater 看起来像这样:

Out[9]: array([1, 1, 1, 1, 1, 1, 0, 0, 0, 0])

colors[greater] 看起来像这样:

array(['green', 'green', 'green', 'green', 'green', 'green', 'red', 'red',
       'red', 'red'], dtype='<U5')

【讨论】:

  • 谢谢。只是好奇,为什么颜色列表必须是一个 numpy 数组?
  • 它没有,它只是让索引更容易。
猜你喜欢
  • 2011-08-19
  • 2012-05-04
  • 2021-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多