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

3
  • another related question: stackoverflow.com/questions/18903750/… Commented Dec 15, 2019 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) Commented Dec 15, 2019 at 20:32
  • Did you try anything? bar.set_color(..) for example? Commented Dec 15, 2019 at 20:33

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

I edited the code to make it consistent with the text you wrote.
Thanks, that was the solution I was looking for.
@kunal I’m glad this solution worked for you. Be sure to accept this answer so the question is marked as such for future users.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.