0

I have a dataset that consists of datetime.datetime objects in a list called x and a list of ints called 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? 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.

Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143
SImon
  • 17
  • 6
  • For example `colors = ['b' if xi < x_special else 'r' for xi in x]` and then `plt.bar(x, y, color=colors)` ? – JohanC Apr 12 '20 at 19:24
  • Does this answer your question? [Matplotlib different colors for bar graph based on value](https://stackoverflow.com/questions/45274183/matplotlib-different-colors-for-bar-graph-based-on-value) (see the second answer) – DrGorilla.eth Apr 12 '20 at 19:30

1 Answers1

2

You could make a boolean mask, where you return 0 or 1 depending on if the date is greater than another date. Then use this array to get a list of 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])

enter image description here

greater looks like this:

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

And colors[greater] looks like this:

array(['green', 'green', 'green', 'green', 'green', 'green', 'red', 'red',
       'red', 'red'], dtype='<U5')
Nicolas Gervais
  • 33,817
  • 13
  • 115
  • 143