4

I am plotting a bar graph using matplotlib and according to a condition in my code I need to change the color of one of the bar. Is it possible to change the color of a single bar in the plot without plotting a new bar graph, because that would increase the complexity ?

Related: how to change the color of a single bar if condition is True matplotlib

kunal
  • 365
  • 1
  • 4
  • 16
  • another related question: https://stackoverflow.com/questions/18903750/vary-the-color-of-each-bar-in-bargraph-using-particular-value – FObersteiner Dec 15 '19 at 20:21
  • It does not specify what I asked for ? I have already plotted the graph and want to change the color of one bar. (Plotting the graph again with updated colors will be quite complex) – kunal Dec 15 '19 at 20:32
  • Did you try anything? bar.set_color(..) for example? – ImportanceOfBeingErnest Dec 15 '19 at 20:33

1 Answers1

3

matplotlib.pyplot.bar returns a matplotlib.container.BarContainer, in which the individual bars are stored as matplotlib.patches.Rectangle objects. Given that

The container can be treated as a tuple of the patches themselves. Additionally, you can access these and further parameters by the attributes

You can extract the patch for the specific bar or bars you want and change its color. An example:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 5)
bars = plt.bar(x, x)
bars[2].set_color('orange')
plt.show()

enter image description here

William Miller
  • 9,839
  • 3
  • 25
  • 46