Active March 01, 2021    /    Viewed 10056    /    Comments 0    /    Edit

Examples of how to plot a bar chart with a colorbar with matplotlib:

### Plot a bar chart with a colorbar (Example 1)

An example of how to associate a color to each bar and plot a color bar

````import matplotlib.pyplot as plt`
`from matplotlib.cm import ScalarMappable`

`data_x = [0,1,2,3]`
`data_hight = [60,60,80,100]`
`data_color = [200.,600.,0.,750.]`

`data_color_normalized = [x / max(data_color) for x in data_color]`

`fig, ax = plt.subplots(figsize=(15, 4))`

`my_cmap = plt.cm.get_cmap('GnBu')`
`colors = my_cmap(data_color_normalized)`

`rects = ax.bar(data_x, data_hight, color=colors)`

`sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_color)))`

`sm.set_array([])`

`cbar = plt.colorbar(sm)`
`cbar.set_label('Color', rotation=270,labelpad=25)`

`plt.xticks(data_x)    `
`plt.ylabel("Y")`

`plt.title('How to plot a bar chart with a colorbar with matplotlib ?')`

`plt.savefig("bar_chart_with_colorbar_01.png", bbox_inches='tight')`

`plt.show()`
```

### Plot a bar chart with a colorbar: color normalized (Example 2)

To normalize the color between 0 and 1, just replace

````sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_color)))`
```

to

````sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_color_normalized)))`
```

### Plot a bar chart with a colorbar: color associated to bar height (Example 3)

Another example: using a colorbar to show bar height

````import matplotlib.pyplot as plt`
`from matplotlib.cm import ScalarMappable`

`data_x = [0,1,2,3]`
`data_hight = [60,60,80,100]`

`data_hight_normalized = [x / max(data_hight) for x in data_hight]`

`fig, ax = plt.subplots(figsize=(15, 4))`

`my_cmap = plt.cm.get_cmap('GnBu')`
`colors = my_cmap(data_hight_normalized)`

`rects = ax.bar(data_x, data_hight, color=colors)`

`sm = ScalarMappable(cmap=my_cmap, norm=plt.Normalize(0,max(data_hight)))`

`sm.set_array([])`

`cbar = plt.colorbar(sm)`
`cbar.set_label('Color', rotation=270,labelpad=25)`

`plt.xticks(data_x)    `
`plt.ylabel("Y")`

`plt.title('How to plot a bar chart with a colorbar with matplotlib ?')`

`plt.savefig("bar_chart_with_colorbar_03.png", bbox_inches='tight')`

`plt.show()`
```

### References

##### Daidalos

Hi, I am Ben.

I have developed this web site from scratch with Django to share with everyone my notes. If you have any ideas or suggestions to improve the site, let me know ! (you can contact me using the form in the welcome page). Thanks!

Did you find this content useful ?, If so, please consider donating a tip to the author(s). MoonBooks.org is visited by millions of people each year and it will help us to maintain our servers and create new contents.

Amount