My problem lies within the colorbar after generating subplots based on a data within certain gridpoints.
If I generate a single Snapshot, the colorbar will appear:
fig1, ax = plt.subplots()
im = ax.imshow(data[0])
fig1.colorbar(im, ax=ax,label='blublub')
ax.set_title = ('blabla')
But when I generate a loop for several subplots like, I cannot implement showing the colorbar at least once at the bottom of the figure.
fig = plt.figure(figsize = (15, 15))
for t in range(17):
plt.subplot(5, 5, t 1)
plt.pcolor(x1grid, x2grid, data[t])
txt = "t = {t:.1f}"
plt.title(txt.format(t = time[t]))
I reviewed all questions on this platform, but could not implement a single one within my code. If my question is covered by already existing one, pls excuse me. I will review it and delete my post.
Thanks in advance Maria
CodePudding user response:
If you want to add a colorbar to each subplot in your loop, you can use the plt.colorbar() function in the same way as you did for the single subplot. However, instead of passing the im object as the first argument, you should pass the mappable object returned by plt.pcolor(). For example:
fig = plt.figure(figsize = (15, 15))
for t in range(17):
plt.subplot(5, 5, t 1)
pc = plt.pcolor(x1grid, x2grid, data[t])
plt.colorbar(pc, label='blublub')
txt = "t = {t:.1f}"
plt.title(txt.format(t = time[t]))
CodePudding user response:
I hope that you understand that, if you want to use a single colormap, you should use a single normalization for all of your plots. That said, here it is your figure with your colormap
And here it's the code
import numpy as np
import matplotlib.pyplot as plt
# Let's fake the data…
Nt, Nxy = 17, 201
x = y = np.linspace(0, 10, Nxy)
x, y = np.meshgrid(x,y)
data = np.empty((Nt, Nxy, Nxy))
for t in range(Nt):
t4 = 1 t/4
data[t] = t4*(1 np.sin( t4*x y/t4))
# as I said, we need a single normalize object for all the data
norm = plt.Normalize(round(data.min()), round(data.max()))
# now we plot the data's elements
fig = plt.figure(figsize = (8, 8), layout='constrained')
# because we'll later need a list of all axes …
axes = []
for t in range(17):
axes.append(plt.subplot(5, 5, t 1))
axes[-1].pcolor(x, y, data[t], norm=norm)
axes[-1].set_title('t=' str(t))
# decorate the figure and place the colormap
fig.suptitle('A single colormap, a single normalization scale\n',
size='xx-large')
fig.colorbar(plt.cm.ScalarMappable(norm=norm),
orientation='horizontal',
# ax = axes instructs the colormap to extend over all axes
ax=axes,
# but it's to much, so we shrink it to 75%
shrink=0.75,
# and make it a little slimmer
aspect=30,
)
# I'm satisfied, hence
plt.show()
ps if you want squarish plots, you could a) reduce the figure width or b) play with the aspect of the plots.