I am trying to align the matplotlib plot with its colorbar. However, when there is a tick on the top of the colormap, the figure itself shrinks a little bit:
Is there a way to equalize this distance (blue arrows) consistently?
For generating the plot, I am using following code:
import matplotlib as mpl
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots(1, 1, figsize=(8, 8))
ax.plot(...)
divider = make_axes_locatable(plt.gca())
cax = divider.append_axes('right', '5%', pad='3%')
sm = plt.cm.ScalarMappable(cmap=plt.get_cmap('viridis'),
norm=mpl.colors.Normalize(vmin=0, vmax=60))
sm.set_array([])
fig.colorbar(sm, cax=cax)
plt.tight_layout()
plt.savefig('pic.png', dpi=500)
Related
I'm making some interactive plots and I would like to add a colorbar legend. I don't want the colorbar to be in its own axes, so I want to add it to the existing axes. I'm having difficulties doing this, as most of the example code I have found creates a new axes for the colorbar.
I have tried the following code using matplotlib.colorbar.ColorbarBase, which adds a colorbar to an existing axes, but it gives me strange results and I can't figure out how to specify attributes of the colorbar (for instance, where on the axes it is placed and what size it is)
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.cm import coolwarm
import numpy as np
x = np.random.uniform(1, 10, 10)
y = np.random.uniform(1, 10, 10)
v = np.random.uniform(1, 10, 10)
fig, ax = plt.subplots()
s = ax.scatter(x, y, c=v, cmap=coolwarm)
matplotlib.colorbar.ColorbarBase(ax=ax, cmap=coolwarm, values=sorted(v),
orientation="horizontal")
Using fig.colorbar instead ofmatplotlib.colorbar.ColorbarBase still doesn't give me quite what I want, and I still don't know how to adjust the attributes of the colorbar.
fig.colorbar(s, ax=ax, cax=ax)
Let's say I want to have the colorbar in the top left corner, stretching about halfway across the top of the plot. How would I go about doing that?
Am I better off writing a custom function for this, maybe using LineCollection?
This technique is usually used for multiple axis in a figure. In this context it is often required to have a colorbar that corresponds in size with the result from imshow. This can be achieved easily with the axes grid tool kit:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
im = ax.imshow(data, cmap='bone')
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
The colorbar has to have its own axes. However, you can create an axes that overlaps with the previous one. Then use the cax kwarg to tell fig.colorbar to use the new axes.
For example:
import numpy as np
import matplotlib.pyplot as plt
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
cax = fig.add_axes([0.27, 0.8, 0.5, 0.05])
im = ax.imshow(data, cmap='gist_earth')
fig.colorbar(im, cax=cax, orientation='horizontal')
plt.show()
Couldn't add this as a comment, but in case anyone is interested in using the accepted answer with subplots, the divider should be formed on specific axes object (rather than on the numpy.ndarray returned from plt.subplots)
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots(ncols=2, nrows=2)
for row in ax:
for col in row:
im = col.imshow(data, cmap='bone')
divider = make_axes_locatable(col)
cax = divider.append_axes('right', size='5%', pad=0.05)
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
It seems like some of the methods that work for matplotlib 2D might not be working for matplotlib 3D. I'm not sure.
I'd like to remove the tick marks from all axes, and extend the edge color from the bottom and sides to the top as well. The farthest I have gotten is being able to draw the ticks as white, which looks bad as they are rendered on top of the edge lines.
Below is a big chunk of self-contained code that results in the following image. Any help is much appreciated!
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import animation
from mpl_toolkits.mplot3d import Axes3D
mpl.rcParams['ytick.color'] = 'white'
#mpl.rcParams['ytick.left'] = False
sample = np.random.random_integers(low=1,high=5, size=(10,3))
# Create a figure and a 3D Axes
fig = plt.figure(figsize=(5,5))
ax = Axes3D(fig)
#ax.w_xaxis.set_tick_params(color='white')
#ax.axes.tick_params
ax.axes.tick_params(bottom=False, color='blue')
##['size', 'width', 'color', 'tickdir', 'pad', 'labelsize',
##'labelcolor', 'zorder', 'gridOn', 'tick1On', 'tick2On',
##'label1On', 'label2On', 'length', 'direction', 'left', 'bottom',
##'right', 'top', 'labelleft', 'labelbottom',
##'labelright', 'labeltop', 'labelrotation']
colors = np.mean(sample[:, :], axis=1)
ax.scatter(sample[:,0], sample[:,1], sample[:,2],
marker='o', s=20, c=colors, alpha=1)
ax.tick_params(color='red')
frame1 = plt.gca()
frame1.axes.xaxis.set_ticklabels([])
frame1.axes.yaxis.set_ticklabels([])
frame1.axes.zaxis.set_ticklabels([])
#frame1.axes.yaxis.set_tick_params(color='white')
To answer the first bit of the question, about tick removal,
it's probably easiest to just disable the tick lines:
for line in ax.xaxis.get_ticklines():
line.set_visible(False)
for line in ax.yaxis.get_ticklines():
line.set_visible(False)
for line in ax.zaxis.get_ticklines():
line.set_visible(False)
E.g.:
import numpy as np
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import animation
from mpl_toolkits.mplot3d import Axes3D
sample = np.random.random_integers(low=1,high=5, size=(10,3))
# Create a figure and a 3D Axes
fig = plt.figure(figsize=(5,5))
ax = Axes3D(fig)
colors = np.mean(sample[:, :], axis=1)
ax.scatter(sample[:,0], sample[:,1], sample[:,2],
marker='o', s=20, c=colors, alpha=1)
ax = plt.gca()
ax.xaxis.set_ticklabels([])
ax.yaxis.set_ticklabels([])
ax.zaxis.set_ticklabels([])
for line in ax.xaxis.get_ticklines():
line.set_visible(False)
for line in ax.yaxis.get_ticklines():
line.set_visible(False)
for line in ax.zaxis.get_ticklines():
line.set_visible(False)
For newer versions (e.g. matplotlib 3.5.1) a lot of formatting can be done via mpl_toolkits.mplot3d.axis3d._axinfo:
import numpy as np
from matplotlib import pyplot as plt
sample = np.random.randint(low=1,high=5, size=(10,3))
# Create a figure and a 3D Axes
fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(projection='3d')
colors = np.mean(sample[:, :], axis=1)
ax.scatter(sample[:,0], sample[:,1], sample[:,2],
marker='o', s=20, c=colors, alpha=1)
for axis in [ax.xaxis, ax.yaxis, ax.zaxis]:
axis.set_ticklabels([])
axis._axinfo['axisline']['linewidth'] = 1
axis._axinfo['axisline']['color'] = (0, 0, 0)
axis._axinfo['grid']['linewidth'] = 0.5
axis._axinfo['grid']['linestyle'] = "-"
axis._axinfo['grid']['color'] = (0, 0, 0)
axis._axinfo['tick']['inward_factor'] = 0.0
axis._axinfo['tick']['outward_factor'] = 0.0
axis.set_pane_color((0.95, 0.95, 0.95))
plt.show()
Consider this example
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
plt.subplot(121)
img = plt.imshow([np.arange(0,1,.1)],aspect="auto")
ax = plt.gca()
divider = make_axes_locatable(ax)
cax = divider.append_axes("bottom", size="3%", pad=0.5)
plt.colorbar(img, cax=cax, orientation='horizontal')
plt.subplot(122)
plt.plot(range(2))
plt.show()
I want to make these two figures (plot region without colorbar) of the same size.
The size is automatically adjusted if the colorbar is plotted vertically or if two rows are used (211, 212) instead of two columns.
One can basically do the same for the second subplot as for the first, i.e. create a divider and append an axes with identical parameters, just that in this case, we don't want a colorbar in the axes, but instead simply turn the axis off.
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
ax = plt.subplot(121)
img = ax.imshow([np.arange(0,1,.1)],aspect="auto")
divider = make_axes_locatable(ax)
cax = divider.append_axes("bottom", size="3%", pad=0.5)
plt.colorbar(img, cax=cax, orientation='horizontal')
ax2 = plt.subplot(122)
ax2.plot(range(2))
divider2 = make_axes_locatable(ax2)
cax2 = divider2.append_axes("bottom", size="3%", pad=0.5)
cax2.axis('off')
plt.show()
You can now do this without recourse to an extra toolkit by using constrained_layout:
import numpy as np
import matplotlib.pyplot as plt
fig, axs = plt.subplots(1, 2, constrained_layout=True)
ax = axs[0]
img = ax.imshow([np.arange(0,1,.1)],aspect="auto")
fig.colorbar(img, ax=ax, orientation='horizontal')
axs[1].plot(range(2))
plt.show()
How can I keep seaborn.despine from putting both of my y-scales onto the left side of my plot?
The best I've come up with so far is:
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_style("white")
fig, ax = plt.subplots()
ax.plot(np.random.rand(10))
ax2 =ax.twinx()
ax2.plot(100*np.random.rand(10))
sns.despine(ax=ax, right=True, left=True)
sns.despine(ax=ax2, left=True, right=False)
But any other combination will either not despine the y-axes or put the right axis onto the left.
Output of the above: (desired output has no spines, just numbers on left and right)
I guess that's what you want then.
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
sns.set_style("white")
fig, ax = plt.subplots()
ax.plot(np.random.rand(10))
ax2 =ax.twinx()
ax2.plot(100*np.random.rand(10))
sns.despine(ax=ax, right=True, left=True)
sns.despine(ax=ax2, left=True, right=False)
ax2.spines['right'].set_color('white')
I have a matplotlib plot with a colorbar attached. I want to position the colorbar so that it is horizontal, and underneath my plot.
I have almost done this via the following:
plt.colorbar(orientation="horizontal",fraction=0.07,anchor=(1.0,0.0))
But the colorbar is still overlapping with the plot slightly (and the labels of the x axis). I want to move the colorbar further down, but I can't figure out how to do it.
using padding pad
In order to move the colorbar relative to the subplot, one may use the pad argument to fig.colorbar.
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")
fig.colorbar(im, orientation="horizontal", pad=0.2)
plt.show()
using an axes divider
One can use an instance of make_axes_locatable to divide the axes and create a new axes which is perfectly aligned to the image plot. Again, the pad argument would allow to set the space between the two axes.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np; np.random.seed(1)
fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")
divider = make_axes_locatable(ax)
cax = divider.new_vertical(size="5%", pad=0.7, pack_start=True)
fig.add_axes(cax)
fig.colorbar(im, cax=cax, orientation="horizontal")
plt.show()
using subplots
One can directly create two rows of subplots, one for the image and one for the colorbar. Then, setting the height_ratios as gridspec_kw={"height_ratios":[1, 0.05]} in the figure creation, makes one of the subplots much smaller in height than the other and this small subplot can host the colorbar.
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)
fig, (ax, cax) = plt.subplots(nrows=2,figsize=(4,4),
gridspec_kw={"height_ratios":[1, 0.05]})
im = ax.imshow(np.random.rand(11,16))
ax.set_xlabel("x label")
fig.colorbar(im, cax=cax, orientation="horizontal")
plt.show()
Edit: Updated for matplotlib version >= 3.
Three great ways to do this have already been shared in this answer.
The matplotlib documentation advises to use inset_locator. This would work as follows:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import numpy as np
rng = np.random.default_rng(1)
fig, ax = plt.subplots(figsize=(4,4))
im = ax.imshow(rng.random((11, 16)))
ax.set_xlabel("x label")
axins = inset_axes(ax,
width="100%",
height="5%",
loc='lower center',
borderpad=-5
)
fig.colorbar(im, cax=axins, orientation="horizontal")