0

Question

For multiple subplots to have a shared colorbar, please suggest a way.

I need one shared colorbar, but currently asymmetric plots get created which does not look nice.

%matplotlib inline
fig = plt.figure(figsize=(12, 8))
plt.subplot(121)
plt.scatter(
    projected_3d[:, 0], 
    projected_3d[:, 1],
    c=y_train, 
    edgecolor='none', 
    alpha=0.5,
    cmap=plt.cm.get_cmap('nipy_spectral', 10)
)
plt.xlabel('PC1')
plt.ylabel('PC2')
plt.colorbar(ax=plt.gca(), orientation="horizontal")

plt.subplot(122)
plt.scatter(
    projected_3d[:, 0], 
    projected_3d[:, 2],
    c=y_train, 
    edgecolor='none', 
    alpha=0.5,
    cmap=plt.cm.get_cmap('nipy_spectral', 10)
)
plt.xlabel('PC1')
plt.ylabel('PC3')

plt.show()

enter image description here


Update

Already answered in Matplotlib 2 Subplots, 1 Colorbar.

Using make_axes is even easier and gives a better result. It also provides possibilities to customise the positioning of the colorbar. Also note the option of subplots to share x and y axes.

Without using make_axes, the layout gets corrupt.

mon
  • 18,789
  • 22
  • 112
  • 205
  • Hi @ImportanceOfBeingErnest, they use "imshow" but in this case, it is plot which does not return path. – mon Nov 01 '19 at 12:23
  • What *path* is it you're talking about? The question seems to be about the position of the colorbar, right? So it's the same for imshow and scatter. – ImportanceOfBeingErnest Nov 01 '19 at 12:33
  • As per OP statement, voting to close as Duplicate of [Matplotlib 2 Subplots, 1 Colorbar](https://stackoverflow.com/questions/13784201/matplotlib-2-subplots-1-colorbar) – Trenton McKinney Nov 02 '19 at 02:05

0 Answers0