Place legend above the ax at a consistent distance - python

I'm trying to place a legend just above the ax in matplotlib using ax.legend(loc=(0, 1.1)); however, if I change the figure size from (5,5) to (5,10) the legend shows up at a different distance from the top edge of the plot.
Is there any way to reference the top edge of the plot and offset it a set distance from it?
Thanks

There is a constant distance between the legend bounding box and the axes by default. This is set via the borderaxespad parameter. This defaults to the rc value of rcParams["legend.borderaxespad"], which is usually set to 0.5 (in units of the fontsize).
So essentially you get the behaviour you're asking for for free. Mind however that you should specify the loc to the corner of the legend from which that padding is to be taken. I.e.
import numpy as np
import matplotlib.pyplot as plt
for figsize in [(5,4), (5,9)]:
fig, ax = plt.subplots(figsize=figsize)
ax.plot([1,2,3], label="label")
ax.legend(loc="lower left", bbox_to_anchor=(0,1))
plt.show()
For more detailed explanations on how to position legend outside the axes, see How to put the legend out of the plot. Also relevant: How to specify legend position in matplotlib in graph coordinates

Related

Shrink and anchor matplotlib colorbar

How do I use colorbar attributes such as in this snippet:
import seaborn as sns
uniform_data = np.random.rand(10, 12) # random data
ax = sns.heatmap(uniform_data)
cbar = ax.collections[0].colorbar
plt.show()
To shrink the colorbar and put it to the bottom and anchored to the lower left corner (that is, NOT centered)?
Something like this, but with the colorbar shrunk to, let's say 70% and anchored to the bottom left
I am unsure how to search for the methods as cbar.set_location() is not available.
If you want infinite customizability, you need to go more low level than you will get with seaborn, which gives convenience, but can't have knobs for everything.
The most straightforward way to get what you want is to place the colorbar axes manually. Note that you will need to play with the y offset, which I set here to -0.2.
import matplotlib.pyplot as plt
import numpy as np
uniform_data = np.random.rand(10, 12) # random data
fig, ax = plt.subplots(layout='constrained')
pc = ax.imshow(uniform_data)
cbax = ax.inset_axes([0, -0.2, 0.7, 0.05], transform=ax.transAxes)
fig.colorbar(pc, ax=ax, cax=cbax, shrink=0.7, orientation='horizontal')
plt.show()
You could create the colorbar via seaborn, extract its position, adapt it and set it again:
from matplotlib import pyplot as plt
import seaborn as sns
import numpy as np
uniform_data = np.random.rand(10, 12)
ax = sns.heatmap(uniform_data, cmap='rocket_r', cbar_kws={'orientation': 'horizontal', 'ticks': np.linspace(0, 1, 6)})
cax = ax.collections[0].colorbar.ax # get the ax of the colorbar
pos = cax.get_position() # get the original position
cax.set_position([pos.x0, pos.y0, pos.width * 0.6, pos.height]) # set a new position
cax.set_frame_on(True)
cax.invert_xaxis() # invert the direction of the colorbar
for spine in cax.spines.values(): # show the colorbar frame again
spine.set(visible=True, lw=.8, edgecolor='black')
plt.show()
Note that you need cbar_kws={'orientation': 'horizontal'} for a horizontal colorbar that by default is aligned with the x-axis.
After using .set_position, something like plt.tight_layout() won't work anymore.
About your new questions:
cax.invert_xaxis() doesn't invert the colorbar direction
Yes it does. You seem to want to reverse the colormap. Matplotlib's convention is to append _r to the colormap name. In this case, seaborn is using the rocket colormap, rocket_r would be the reverse. Note that changing the ticks doesn't work the way you try it, as these are just numeric positions which will be sorted before they are applied.
If you want to show 0 and 1 in the colorbar (while the values in the heatmap are e.g. between 0.001 and 0.999, you could use vmin and vmax. E.g. sns.heatmap(..., vmin=0, vmax=1). vmin and vmax are one way to change the mapping between the values and the colors. By default, vmin=data.min() and vmax=data.max().
To show the colorbar outline: Add a black frame around a colorbar
ax.collections[0].colorbar is a colorbar, which in the latest versions also supports some functions to set ticks
ax.collections[0].colorbar.ax is an Axes object (a subplot). Matplotlib creates a small subplot on which the colorbar will be drawn. axs support a huge number of functions to change how the subplot looks or to add new elements. Note that a stackoverflow answer isn't meant to put of full matplotlib tutorial. The standard tutorials could be a starting point.

adjust matplotlib subplot spacing after tight_layout

I would like to minimize white space in my figure. I have a row of sub plots where four plots share their y-axis and the last plot has a separate axis.
There are no ylabels or ticklabels for the shared axis middle panels.
tight_layout creates a lot of white space between the the middle plots as if leaving space for tick labels and ylabels but I would rather stretch the sub plots. Is this possible?
import matplotlib.gridspec as gridspec
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
fig = plt.figure()
gs = gridspec.GridSpec(1, 5, width_ratios=[4,1,4,1,2])
ax = fig.add_subplot(gs[0])
axes = [ax] + [fig.add_subplot(gs[i], sharey=ax) for i in range(1, 4)]
axes[0].plot(np.random.randint(0,100,100))
barlist=axes[1].bar([1,2],[1,20])
axes[2].plot(np.random.randint(0,100,100))
barlist=axes[3].bar([1,2],[1,20])
axes[0].set_ylabel('data')
axes.append(fig.add_subplot(gs[4]))
axes[4].plot(np.random.randint(0,5,100))
axes[4].set_ylabel('other data')
for ax in axes[1:4]:
plt.setp(ax.get_yticklabels(), visible=False)
sns.despine();
plt.tight_layout(pad=0, w_pad=0, h_pad=0);
Setting w_pad = 0 is not changing the default settings of tight_layout. You need to set something like w_pad = -2. Which produces the following figure:
You could go further, to say -3 but then you would start to get some overlap with your last plot.
Another way could be to remove plt.tight_layout() and set the boundaries yourself using
plt.subplots_adjust(left=0.065, right=0.97, top=0.96, bottom=0.065, wspace=0.14)
Though this can be a bit of a trial and error process.
Edit
A nice looking graph can be achieved by moving the ticks and the labels of the last plot to the right hand side. This answer shows you can do this by using:
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
So for your example:
axes[4].yaxis.tick_right()
axes[4].yaxis.set_label_position("right")
In addition, you need to remove sns.despine(). Finally, there is now no need to set w_pad = -2, just use plt.tight_layout(pad=0, w_pad=0, h_pad=0)
Using this creates the following figure:

python matplotlib: how to move the scale to the other side of the axis?

I have this weird thing with the scale of the axis showing out of the figure like:
And what I want to have:
How can I move the scale to the other side of the axis?
x=range(len(ticks))
plt.plot(x,phase1,'r^-',label='$\Delta \phi(U1,I1)$')
plt.plot(x,phase2,'go-',label='$\Delta \phi(U2,I2)$')
plt.plot(x,phase3,'b*-',label='$\Delta \phi(U3,I3)$')
plt.xticks(x,ticks,rotation=45)
plt.xlabel('Messung')
plt.ylabel('$\Delta \phi [^\circ]$')
plt.legend()
plt.show()
The tick_params of your axis can be used to control axes label and ticks location. Set direction to in so that they point into the graph.
And here is a great example if you want different y-axis ranges and colours too.
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.tick_params(direction='in', length=6, width=2, colors='r', right=True, labelright='on')
plt.show()
You can use plt.tick_params() to adjust the behaviour of the ticks, documentation can be found here.
For your example you want the ticks to appear inside the figure. Therefore add
plt.tick_params(direction="in")
to your code. Example:
x=range(len(ticks))
plt.plot(x,phase1,'r^-',label='$\Delta \phi(U1,I1)$')
plt.plot(x,phase2,'go-',label='$\Delta \phi(U2,I2)$')
plt.plot(x,phase3,'b*-',label='$\Delta \phi(U3,I3)$')
plt.xticks(x,ticks,rotation=45)
plt.xlabel('Messung')
plt.ylabel('$\Delta \phi [^\circ]$')
plt.legend()
plt.tick_params(direction="in") # Set ticks inside the figure
plt.show()
You can get the ticks to appear on the top and right side of the figure too as shown in your second screenshot by adding:
plt.tick_params(direction="in",top="on",right="on")
If you wanted to make all figures in your Python script have this behaviour then you can add the following at the top of your script (this might be of interest):
import matplotlib
matplotlib.rcParams['xtick.direction'] = "in"
matplotlib.rcParams['ytick.direction'] = "in"
This will save you having to call plt.tick_params() for each figure, which is helpful if you generate lots of figures.

plot circle on unequal axes with pyplot

I would like to plot a circle on an auto-scaled pyplot-generated graphic. When I run
ax.get_aspect()
hoping for a value with which I could manipulate the axes of a ellipse, pyplot returns:
auto
which is less than useful. What methods would you suggest for plotting a circle on a pyplot plot with unequal axes?
This question is more than one year old, but I too just had this question. I needed to add circles to a matplotlib plot and I wanted to be able to specify the circle's location in the plot using data coordinates, and I didn't want the circle radius to change with panning/zooming (or worse the circle turning into an ellipse).
The best and most simple solution that I've found is simply plot a curve with a single point and include a circle marker:
ax.plot(center_x,center_y,'bo',fillstyle='none',markersize=5)
which gives a nice, fixed-size blue circle with no fill!
It really does depend what you want it for.
The problem with defining a circle in data coordinates when aspect ratio is auto, is that you will be able to resize the figure (or its window), and the data scales will stretch nicely. Unfortunately, this would also mean that your circle is no longer a circle, but an ellipse.
There are several ways of addressing this. Firstly, and most simply, you could fix your aspect ratio and then put a circle on the plot in data coordinates:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = plt.axes()
ax.set_aspect(1)
theta = np.linspace(-np.pi, np.pi, 200)
plt.plot(np.sin(theta), np.cos(theta))
plt.show()
With this, you will be able to zoom and pan around as per usual, but the shape will always be a circle.
If you just want to put a circle on a figure, independent of the data coordinates, such that panning and zooming of an axes did not effect the position and zoom on the circle, then you could do something like:
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = plt.axes()
patch = mpatches.Circle((325, 245), 180, alpha=0.5, transform=None)
fig.artists.append(patch)
plt.show()
This is fairly advanced mpl, but even so, I think it is fairly readable.
HTH,
Building on #user3208430, if you want the circle to always appear at the same place in the axes (regardless of data ranges), you can position it using axes coordinates via transform:
ax.plot(.94, .94, 'ro', fillstyle='full', markersize=5, transform=ax.transAxes)
Where x and y are between [0 and 1]. This example places the marker in the upper right-hand corner of the axes.

matplotlib - subplots with fixed aspect ratio

I have a problem with plotting multiple subplots. I would like to set the PHYSICAL aspect ratio of the subplots to a fixed value.
In my example I have 12 subplots (4 rows and 3 columns) on a landscape A4 figure. There all subplots are nicely placed on the whole figure, and for all subplots the height is nearly equal to the width.
But if I change the layout of my figure to portrait, the subplots are stretched vertically.
And this is exactly what should not happen. I would like to have the same height and width of the subplots as on the landscape figure. Is there a possibility that the aspect ratio of the subplots stay the same?
Thanks in advance,
Peter
EDIT:
I have found a workaround. But this just works for non-logarithmic axes...
aspectratio=1.0
ratio_default=(ax.get_xlim()[1]-ax.get_xlim()[0])/(ax.get_ylim()[1]-ax.get_ylim()[0])
ax.set_aspect(ratio_default*aspectratio)
Actually, what you're wanting is quite simple... You just need to make sure that adjustable is set to 'box' on your axes, and you have a set aspect ratio for the axes (anything other than 'auto').
You can either do this with the adjustable kwarg when you create the subplots. Alternatively, you can do this after their creation by calling ax.set_adjustable('box'), or by calling ax.set_aspect(aspect, adjustable='box') (where aspect is either 'equal' or a number).
Now, regardless of how the figure is resized, the subplots will maintain the same aspect ratio.
For example:
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1, adjustable='box', aspect=0.3)
ax2 = fig.add_subplot(2,1,2)
ax1.plot(range(10))
ax2.plot(range(10))
plt.show()
Now, compare how the top subplot responds to resizing, vs. how the bottom subplot responds:
The initial plot
Resized to a vertical layout:
Resized to a horizontal layout:
Your workaround works for me. After plotting the data, I call the following function:
def fixed_aspect_ratio(ratio):
'''
Set a fixed aspect ratio on matplotlib plots
regardless of axis units
'''
xvals,yvals = gca().axes.get_xlim(),gca().axes.get_ylim()
xrange = xvals[1]-xvals[0]
yrange = yvals[1]-yvals[0]
gca().set_aspect(ratio*(xrange/yrange), adjustable='box')
In reply to the remark about the solution not working for logarithmic plots in the edit to the original question - you need to adapt as follows:
def fixed_aspect_ratio_loglog(ratio):
'''
Set a fixed aspect ratio on matplotlib loglog plots
regardless of axis units
'''
xvals,yvals = gca().axes.get_xlim(),gca().axes.get_ylim()
xrange = log(xvals[1])-log(xvals[0])
yrange = log(yvals[1])-log(yvals[0])
gca().set_aspect(ratio*(xrange/yrange), adjustable='box')
(Adaptation for semilog plots should now be obvious)

Categories

Resources