How to add color bars in matplotlib bar plot

Introduction

When bar plotting is done with matplotlib, the color bar cannot be added because the Mappable object is not returned.

>>> import matplotli.pyplot as plt
>>> plt.bar(0, 1)
<Container object of 1 artists>

But I want to add a color bar somehow! So I tried it.

0. Create appropriate data

First of all, let's create appropriate data. Here, the data is created on the assumption that a figure with bars 1 to 3 in height is stacked.

>>> import numpy as np
>>> dheight = np.random.choice([1, 2, 3], size=10)
>>> data = np.random.choice([1, 2, 3, 4, 5], size=dheight.size)
>>> print data
[1 1 1 4 5 2 1 2 2 4]

This time, we will color according to the value of the variable called data created here.

Now that we have created the appropriate data, we can finally start drawing.

1. Create a Normalize function

First, in the color bar of matplotlib, colors are defined in the color map corresponding to the values between 0 and 1. Therefore, if you want to color according to the values 1 to 5 like this time, you need a function (like object) for standardization. A class called Normalize can create it.

>>> from matplotlib.colors import Normalize
>>> norm = Normalize(vmin=data.min(), vmax=data.max())
>>> print norm(1), norm(2), norm(3)
0.0 0.25 0.5

As you can see by actually entering a value, if you give a value to this object called norm, it is standardized so that vmin is 0 and vmax is 1.

2. Creating a Mappable object

Next, create a Mappable object. This time, we will create a Mappable according to jet, which is the default color map of matplotlib.

>>> from matplotlib.cm import ScalarMappable, get_cmap
>>> cmap = get_cmap('jet')
>>> mappable = ScalarMappable(cmap=cmap, norm=norm)
>>> mappable._A = []

3. Plot the data

Once you're ready, you can actually plot the data.

>>> import matplotlib.pyplot as plt
>>> bottom = 0.
>>> for dh, v in zip(dheight, data):
...     plt.bar(0, dh, width=1, bottom=bottom, color=cmap(norm(v)))
...     bottom += dh
>>> cbar = plt.colorbar(mappable)

Since the data plotted this time is [1 1 1 4 5 2 1 2 2 4], if the color corresponding to this value is in the color bar, the color bar can be drawn without any problem.

4. Label

Finally, label it and it's done. This time, the label is attached by dividing the data between the minimum value and the maximum value into five parts.

>>> cbar = plt.colorbar(mappable)
>>> ticks = np.linspace(norm.vmin, norm.vmax, 5)
>>> cbar.set_ticks(ticks)
>>> cbar.ax.set_yticklabels([str(s) for s in ticks])
[<matplotlib.text.Text at 0x7f36ac9b01d0>,
 <matplotlib.text.Text at 0x7f36ac9bb850>,
 <matplotlib.text.Text at 0x7f36ac98e550>,
 <matplotlib.text.Text at 0x7f36ac98ec50>,
 <matplotlib.text.Text at 0x7f36ac996390>]

5. Completed!

This is the end.

>>> plt.show()

index.png

The color corresponding to the value of [1 1 1 4 5 2 1 2 2 4] was drawn safely.

Helpful page

Recommended Posts

How to add color bars in matplotlib bar plot
How to suppress display error in matplotlib
Add cumulative ratio to matplotlib bar chart
How to change editor color in PyCharm
[Python] How to draw a histogram in Matplotlib
How to plot autocorrelation and partial autocorrelation in python
2D plot in matplotlib
How to eliminate garbled characters in matplotlib output image
How to add page numbers to PDF files (in Python)
How to pass matplotlib backend settings in environment variables
[Python] How to draw a scatter plot with Matplotlib
Stackable bar plot with matplotlib
How to develop in Python
How to add new data (lines and plots) using matplotlib
How to plot a lot of legends by changing the color of the graph continuously with matplotlib
[Python] How to do PCA in Python
How to use classes in Theano
How to write soberly in pandas
How to collect images in Python
How to change the color of just the button pressed in Tkinter
Add cumulative ratio to matplotlib histogram
How to update Spyder in Anaconda
How to use SQLite in Python
How to add sudo when debugging
How to run matplotlib on heroku
How to convert 0.5 to 1056964608 in one shot
How to reflect CSS in Django
How to kill processes in bulk
How to use Mysql in python
How to wrap C in Python
How to use ChemSpider in Python
How to change vim color scheme
How to use PubChem in Python
How to add AWS EBS volume
How to run TensorFlow 1.0 code in 2.0
Continuously color with matplotlib scatter plot
How to handle Japanese in Python
How to log in to Docker + NGINX
How to display legend marks in one with Python 2D plot
How to call PyTorch in Julia
[Small story] How to save matplotlib graphs in a batch with Jupyter
How to plot galaxy visible light data using OpenNGC database in python
How to draw a bar graph that summarizes multiple series with matplotlib
How to use calculated columns in CASTable
How to display the progress bar (tqdm)
[Introduction to Python] How to use class in Python?
Specify the color in the matplotlib 2D map
How to access environment variables in Python
How to dynamically define variables in Python
How to add a package with PyCharm
How to do R chartr () in Python
How to draw a graph using Matplotlib
How to convert csv to tsv in CLI
How to delete expired sessions in Django
[Itertools.permutations] How to put permutations in Python
How to use Google Test in C
How to implement nested serializer in drf-flex-fields
How to work with BigQuery in Python
How to execute commands in jupyter notebook
How to do'git fetch --tags' in GitPython
How to display multiplication table in python