Is there a way to color the bars of a barchart based on the bar's value. For example:
- values below -0.5: red
- values between -0.5 to 0: green
- values between 0 to 08: blue
- etc
I have found some basic examples of bar coloring but nothing which can cater for value ranges, such as the above examples.
UPDATE:
Thank you kikocorreoso for your suggestion. This works great when both axes are numbers as per your example. However in my case my original data structure is a pandas dataframe. I then use df.stack() and plot the result. This means that the dataframes rows/columns become the x axis of the plot and the dataframe cells are the Y axis (bars).
I have tried masking as per your example but it doesn't seem to work when the Y axis are numbers and the X axis are names. eg:
col1 col2 col3 col4
row1 1 2 3 4
row2 5 6 7 8
row3 9 10 11 12
row4 13 14 15 16
The above dataframe needs to be plotted as a barchart with the row/column combinations forming the x-axis. Each cell value will be a bar. And ultimately, coloring the bars as per the original question. Thanks
You can change the color of bars in a barplot using color argument. RGB is a way of making colors. You have to to provide an amount of red, green, blue, and the transparency value to the color argument and it returns a color.
To set color for bars in a Bar Plot using Matplotlib PyPlot API, call matplotlib. pyplot. bar() function, and pass required color value(s) to color parameter of bar() function. Of course, there are other named parameters, but for simplicity, only color parameter is given.
there is no color parameter listed where you might be able to set the colors for your bar graph.
You can also set the color individually for each point/bar if you change the data array to be configuration objects instead of numbers.
You could use masks for your datasets. A basic example could be the following:
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(10)
y = np.arange(10) * 0.1
mask1 = y < 0.5
mask2 = y >= 0.5
plt.bar(x[mask1], y[mask1], color = 'red')
plt.bar(x[mask2], y[mask2], color = 'blue')
plt.show()
The result should be:
UPDATE:
As you updated your question I update the code. For your simple case, and if I understood correctly, you could do the following (ugly) hack:
import pandas as pd
df = pd.DataFrame({'col1':[1,2,3], 'col2':[4,5,6]},
index = ['row1','row2','row3'])
dfstacked = df.stack()
mask = dfstacked <= 3
colors = np.array(['b']*len(dfstacked))
colors[mask.values] = 'r'
dfstacked.plot(kind = 'bar', rot = 45, color = colors)
plt.show()
Or use a more OO solution.
The code briefly explained:
dfstacked
dataframe has a MultiIndex
the ticks are not well printed so I use the rot
keyword to rotate them. If you want to automate it in order to get a nice plot you can use plt.tight_layout()
before plt.show()
.I hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With