I have a nrows=2
by ncols=2
subplot. I am trying to make a single orientation='vertical'
colorbar, for which the left ticks correspond to the first row and the right ticks correspond to the second row. I cannot figure out how to make two-sided ticks. Below is an example code to make the colorbar.
import numpy as np
import matplotlib.pyplot as plt
# Initialize Data Parameters
xmu, ymu = 5, 50 # Normal Distribution values for first row
xsig, ysig = 2, 10 # Normal Distribution values for second row
size = 100 # Number of datapoints
shp = (10, 10) # shape of Z array
levels1 = np.linspace(0, 10, 11, dtype=int) # ticks of first colorbar
levels2 = np.linspace(20, 80, 11, dtype=int) # ticks of second colorbar
# Initialize Data
x1 = np.random.normal(xmu, xsig, size) # row=1 x col=1
x2 = np.random.normal(xmu, xsig, size) # row=1 x col=2
y1 = np.random.normal(ymu, ysig, size) # row=2 x col=1
y2 = np.random.normal(ymu, ysig, size) # row=2 x col=2
data = [x1, x2, y1, y2]
levels = [levels1, levels1, levels2, levels2]
def get_Z(datum, shape=shp):
""" returns Z array, applied in zip routine below """
return datum.reshape(shape)
fig, axes = plt.subplots(nrows=2, ncols=2)
for ax, datum, level in zip(axes.ravel(), data, levels):
im = ax.imshow(get_Z(datum), vmin=min(level), vmax=max(level))
# create axes for colorbar and set colorbar ticks
cax = fig.add_axes([0.9, 0.1, 0.03, 0.8])
cbar = fig.colorbar(im, cax=cax)
cbar.set_ticks(levels2)
cbar.set_ticklabels(levels2)
plt.show()
plt.close(fig)
Is there a simple matplotlib way of adding the ticks for the first row and second row to the left and right side of the colorbar, respectively?
(My goal is to apply matplotlib example to correct the values of the colorbar; still playing with that part. Not sure if that's relevant to the problem or not. My actual use case is to make two separate subplots; the first is a subplot of surface maps and the second is a subplot of contour plots.)