简体   繁体   English

如何在 matplotlib 日期条形图中的某个日期之后为所有条形着色

[英]How to colour all bars after a certain date in a matplotlib date bar chart

I have a dataset that consists of datetime.datetime objects in a list called x and a list of ints called y .我有一个数据集,其中包含一个名为x的列表中的datetime.datetime对象和一个名为y的整数列表。 I'm plotting them like so:我正在像这样绘制它们:

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

How would I go about colouring all the bars after a given date another colour?我将如何 go 在给定日期后为所有条着色另一种颜色? I know I can get a list of bars by assigning the result of plt.bar(x, y) but I've never messed around with matplotlib beyond making simple plots.我知道我可以通过分配plt.bar(x, y)的结果来获得条形列表,但除了制作简单的绘图之外,我从来没有弄乱过matplotlib

You could make a boolean mask, where you return 0 or 1 depending on if the date is greater than another date.您可以制作 boolean 掩码,根据日期是否大于另一个日期,您可以在其中返回 0 或 1。 Then use this array to get a list of colors.然后用这个数组得到一个colors的列表。

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 looks like this: greater看起来像这样:

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

And colors[greater] looks like this: colors[greater]看起来像这样:

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

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

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