1

I am plotting four (and also eight) subplots next to each other with no whitespace. I also need a color bar which is placed to the far right. However, the colors inside the color bar are out of bounds of the color bar edges: it is sticking out at the top and are not covering the bottom.

import matplotlib.pyplot as plt
from matplotlib import gridspec

fig, ax = plt.subplots(nrows=1, ncols=4, figsize=(4*6.4, 4.8))
gs = gridspec.GridSpec(1, 4, hspace=.0, wspace=.0) #height_ratios=[1,2,3,4])

for idx, _ in enumerate(ax):
    ax[idx] = plt.subplot(gs[idx])
    sc = plt.scatter(0.5, 0.5)
    ax[idx].xaxis.set_ticks_position('both')
    ax[idx].yaxis.set_ticks_position('both')
    yticks = ax[idx].get_yticklabels()
    yticks[-1].set_visible(False)
    yticks[0].set_visible(False)
    xticks = ax[idx].get_xticklabels()
    yticks[-1].set_visible(False)
    xticks[0].set_visible(False)

cb_ax = fig.add_axes([ax[3].get_position().x1+0.005,ax[3].get_position().y0,0.01,ax[3].get_position().y1-ax[3].get_position().y0])
cb=fig.colorbar(sc, cax=cb_ax)

plt.show()

fig.savefig('sticking_out.pdf', bbox_inches='tight')

In the minimal working example, I tried to fit the color bar to the height of the figure. The edge of the color bar is perfectly aligned but the colors themselves are shifted upwards (see images below).

enter image description here

enter image description here

Is there an elegant solution to this problem? Perhaps it is also a better way to fit the color bar to the height of the figure?

5
  • It seems to have been affected by thebbox_inches='tight' Commented Mar 12, 2021 at 13:34
  • Thank you for your comment, @r-beginners. If I remove bbox_inches='tight it is still there but less visible. Commented Mar 12, 2021 at 15:21
  • 1
    I can't reproduce the problem. Running on windows10, matplotlib 3.3.4, pycharm. But I do get similar problems if I decrease the default dpi (e.g. fig.savefig('sticking_out.pdf', bbox_inches='tight', dpi=50)). So, you might try to increase the dpi.
    – JohanC
    Commented Mar 12, 2021 at 17:51
  • Thank you, @JohanC. It does appear to improve with choosing a nondefault and high dpi. Do have any idea as to why this happens? Commented Mar 14, 2021 at 10:05
  • 1
    This will be rounding errors. The lower the dpi the less dots to place vertices.
    – JohanC
    Commented Mar 14, 2021 at 10:57

1 Answer 1

0

Thank you, @JohanC for explaining it to me in the comments above. It is solved if use you a higher dpi and it is caused by rounding errors, according to @JohanC. I answered the question myself to "close" it but all credit to @JohanC.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.