Created
May 20, 2020 18:37
-
-
Save Prukutu/7bfd668d792f76b8f99f7a5c9fc877a4 to your computer and use it in GitHub Desktop.
Create a matplotlib figure with a colorbar using gridspec.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import matplotlib.pyplot as plt | |
from matplotlib.gridspec import GridSpec | |
from numpy.random import randint | |
# Generate array of random values | |
data = randint(0, | |
high=100, | |
size=(100, 100)) | |
# GridSpec object. second column will hold colorbar | |
# you can play with the ratio of widths to get the look you want | |
# Can also play with the spacing between subplos using wspace kwarg | |
gs = GridSpec(nrows=1, | |
ncols=2, | |
width_ratios=(100, 5), | |
wspace=.005) | |
# figure object | |
fig = plt.figure() | |
# Add an ax object to draw imshow on. | |
ax = fig.add_subplot(gs[0]) | |
# save imge output so we can supply it when calling colorbar | |
im = ax.imshow(data) | |
# Can use position kwarg to modify position and size of cbar. | |
cbarax = fig.add_subplot(gs[1]), | |
cbar = plt.colorbar(im, | |
orientation='vertical', | |
cax=cbarax) | |
plt.show() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment