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.
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.
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.
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 = []
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.
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>]
This is the end.
>>> plt.show()
The color corresponding to the value of [1 1 1 4 5 2 1 2 2 4] was drawn safely.
Recommended Posts