matplotlib: adding padding/offset to polar plots tick labels - matplotlib

Is there a way to increase the padding/offset of the polar plot tick labels (theta)?
import matplotlib
import numpy as np
from matplotlib.pyplot import figure, show, grid
# make a square figure
fig = figure(figsize=(2, 2))
ax = fig.add_axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c')
ax.set_yticklabels([])
r = np.arange(0, 3.0, 0.01)
theta = 2*np.pi*r
ax.plot(theta, r, color='#ee8d18', lw=3)
ax.set_rmax(2.0)
show()
I'd like to have theta tick labels further away from the polar plot so they don't overlap.

First of all; seeing as how you have specified the figsize to be (2,2) and having the ax occupy 80 % of both the width and height, you have very little space left over to pad the ticklabels. This could cause the ticklabels to be "cut off" at the figure's egdes. This can easily be "fixed" by either
Specifying bigger figsize
Make the ax occupy less space on the (2,2) sized figure
Use smaller fontsize for the ticklabels
or any combination of these. Another, in my opinion better, solution to this "problem" is to use a subplot rather than specifying the Axes's bounds;
ax = fig.add_subplot(111, polar=True, axisbg='#d5de9c')
as this makes it possible to use the method tight_layout() which automatically configures the figure layout to nicely include all elements.
Then over to the real problem at hand; the padding. On a PolarAxes you can set, among other things, the radial placement of the theta-ticks. This is done by specifying the fraction of the polar axes radius where you want the ticklabels to be placed as an argument to the frac parameter of the PolarAxes's set_thetagrids() method. The argument should be a fraction of the axes' radius where you want the ticklabels placed. I.e. for frac < 1 the ticklabels will be placed inside the axes, while for frac > 1 they will be placed outside the axes.
Your code could then be something like this:
import numpy as np
from matplotlib.pyplot import figure, show, grid, tight_layout
# make a square figure
fig = figure(figsize=(2, 2))
ax = fig.add_subplot(111, polar=True, axisbg='#d5de9c')
ax.set_yticklabels([])
r = np.arange(0, 3.0, 0.01)
theta = 2*np.pi*r
ax.plot(theta, r, color='#ee8d18', lw=3)
ax.set_rmax(2.0)
# tick locations
thetaticks = np.arange(0,360,45)
# set ticklabels location at 1.3 times the axes' radius
ax.set_thetagrids(thetaticks, frac=1.3)
tight_layout()
show()
You should try different values for frac to find a value that is best suited for your needs.
If you don't specify a value to the parameter frac as above, i.e. frac has default value None, the code outputs a plot as below. Notice how the radius of the plot is bigger, as the ticklabels don't "occupy as much space" as in the example above.

As of matplotlib 2.1.0, the functionality of the original answer is now deprecated - polar axes now obey to the parameters of ax.tick_params:
ax.tick_params(pad=123)
should do the trick.

Related

How to overlay one pyplot figure on another

Searching easily reveals how to plot multiple charts on one figure, whether using the same plotting axes, a second y axis or subplots. Much harder to uncover is how to overlay one figure onto another, something like this:
That image was prepared using a bitmap editor to overlay the images. I have no difficulty creating the individual plots, but cannot figure out how to combine them. I expect a single line of code will suffice, but what is it? Here is how I imagine it:
bigFig = plt.figure(1, figsize=[5,25])
...
ltlFig = plt.figure(2)
...
bigFig.overlay(ltlFig, pos=[x,y], size=[1,1])
I've established that I can use figure.add_axes, but it is quite challenging getting the position of the overlaid plot correct, since the parameters are fractions, not x,y values from the first plot. It also [it seems to me - am I wrong?] places constraints on the order in which the charts are plotted, since the main plot must be completed before the other plots are added in turn.
What is the pyplot method that achieves this?
To create an inset axes you may use mpl_toolkits.axes_grid1.inset_locator.inset_axes.
Position of inset axes in axes coordinates
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, ax= plt.subplots()
inset_axes = inset_axes(ax,
width=1, # inch
height=1, # inch
bbox_transform=ax.transAxes, # relative axes coordinates
bbox_to_anchor=(0.5,0.5), # relative axes coordinates
loc=3) # loc=lower left corner
ax.axis([0,500,-.1,.1])
plt.show()
Position of inset axes in data coordinates
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, ax= plt.subplots()
inset_axes = inset_axes(ax,
width=1, # inch
height=1, # inch
bbox_transform=ax.transData, # data coordinates
bbox_to_anchor=(250,0.0), # data coordinates
loc=3) # loc=lower left corner
ax.axis([0,500,-.1,.1])
plt.show()
Both of the above produce the same plot
(For a possible drawback of this solution see specific location for inset axes)

Colorbar frame and color not aligned

I have a vexing issue with a colorbar and even after vigorous research I cannot find the question even being asked. I have a plot where I overlay a contour and a pcolormesh and I would like a colorbar to indicate values. That works fine except for one thing:
The colorbar frame and color are offset
The colorbar frame and the actual bar are offset such that below you have a white bit in the frame and on top the color is poking out. While the frame is aligned with the axis as desired, the colorbar is offset.
Here is a working example that emulates the situation I was in, i.e. multiple plots with insets.
import matplotlib.gridspec as gridspec
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
figheight = 4.2 - (2.1 - 49.519 / 25.4)
matplotlib.rcParams['figure.figsize'] = (5.25, figheight)
matplotlib.rcParams['axes.linewidth'] = 0.5
fig = plt.figure()
grid = gridspec.GridSpec(2, 1, height_ratios=[49.519 / 25.4 / figheight, 2.1 / figheight])
ax0 = plt.subplot(grid[0, 0])
ax1 = plt.subplot(grid[1, 0])
plt.tight_layout()
###############################################################################################
#
# Define position of inset
#
###############################################################################################
ax1.axis('off')
pos1 = ax1.get_position()
pos2 = matplotlib.transforms.Bbox([[pos1.x0, pos1.y0],
[.8*pos1.x1,
0.8*pos1.height + pos1.y0]])
left, bottom, width, height = [pos2.x0, pos2.y0, pos2.width, pos2.height]
ax2 = fig.add_axes([left, bottom, width, height])
###############################################################################################
#
# ax2 (inset) plot
#
###############################################################################################
pos2 = ax2.get_position()
ax2.axis('on')
x = np.linspace(0,5)
z = (np.outer(np.sin(x), np.cos(x))+1)*0.5
im = ax2.pcolormesh(z)
c = ax2.contour(z, linewidths=7)
ax2pos = ax2.get_position()
cbar_axis = fig.add_axes([ax2pos.x1+0.05,ax2pos.y0, .02, ax2pos.height])
colorbar = fig.colorbar(im, ax = ax2,
cax = cbar_axis, ticks = [0.1, .5, .9])
colorbar.outline.set_visible(True)
plot = 'Minimal.pdf'
fig.savefig(plot)
plt.close()
The problem persists in both the inline display and the saved .pdf if 'Inline' graphics backend is chosen. Using tight layout or not changes how badly the offset is depending on the size of the bar - same with using PyQT5 rather than inline graphics backend. I thought it was gone when I was changing between the various combinations, but I just realized it's still there.
I would appreciate any input.
As suggested by ImportanceOfBeingErnest I have tried using np.round on the figsize and that didn't change things. While you can fiddle around with sizes to make it look okay, it always stands over on one or the other side by some amount. When I change the graphics backend on Spyder 3 from 'Inline' to 'QT5' the problem becomes less severe with or without rounding. A summary of this is in this picture Colorbar overlap cases. Note that with not rounded and PyQT5 the problem still occurs, but is not as severe.
On inspection, it is clear that the colorbar is not only bleeding out over the top of its axes, but it's also positioned slightly to the left.
So, the problem here appears to be a conflict between the position of the colorbar axis and the colorbar itself when rasterization occurs. You can find more details on this issue in matplotlib's github repository, but I'll summarize what's going on here.
Colorbars are rasterized when the output is produced, so as to avoid artifacting issues during rendering. The position of the colorbar is snapped to the nearest integer pixels during the rasterization process, while the axis is kept where it is supposed to be. Then, when the output is produced, the colorbar falls within borders of fixed pixels of the image, despite the fact that the image is, itself, vectorized. Thus, there are two strategies that can be employed to avoid this mishap.
Use a finer DPI
The conversion from vectorized coordinates to rasterized coordinates takes place assuming a given DPI on the image. By default, this is set to be 72. However, by using more DPI, the overall shift induced by the rasterization process will be smaller, as the closest pixel the colorbar will snap to will be much nearer. Here, we change the output to have fig.savefig(plot,dpi=4000), and the problem goes away:
Note, however, that on my machine, the output size changed from 62 KB to 78 KB due to this change (although the DPI adjustment was also, admittedly, extreme). If you are worried about file sizes, you should pick a lower DPI that fixes the problem.
Use a different colormap
This rasterization happens when more than 50 colors are in the colorbar. Thus, we can do a quick test, setting our colormap to Pastel1 via
im = ax2.pcolormesh(z,cmap='Pastel1'). Here, the colorbar / axis mismatch is mitigated.
As a fallback, adopting a colorbar with fewer than 50 colors should mitigate this problem.
Rasterize the Axis
For completeness, there is also a third option. If you rasterize the colorbar axis, both the axis boundaries and the colormap will be rasterized, and you'll lose the offset. This will also rasterize your labels, and the axis will shift as one, breaking alignment with the nearby axis. For this, you just need to include cbar_axis.set_rasterized(True).
First, a way to overlay a contour and a pcolormesh and create a colorbar would be the following
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import numpy as np
x = np.linspace(0,5)
z = (np.outer(np.sin(x), np.cos(x))+1)*0.5
fig = plt.figure(figsize=(4, 4))
ax = fig.add_subplot(111)
im = ax.pcolormesh(z)
c = ax.contour(z, linewidths=7)
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", "5%", pad="3%")
colorbar = fig.colorbar(im, cax=cax, ticks = [0.1, .5, .9])
plt.show()
Now to the problem from the question. It is of course possible to create the axes to put the colorbar in manually. Replacing the colorbar creation with the code from the question still produces a nice image.
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0,5)
z = (np.outer(np.sin(x), np.cos(x))+1)*0.5
fig = plt.figure(figsize=(4, 4))
ax = fig.add_subplot(111)
plt.subplots_adjust(right=0.8)
im = ax.pcolormesh(z)
c = ax.contour(z, linewidths=7)
ax2pos = ax.get_position()
cbar_axis = fig.add_axes([ax2pos.x1+0.05,ax2pos.y0, .05, ax2pos.height])
colorbar = fig.colorbar(im, ax = ax,
cax = cbar_axis, ticks = [0.1, .5, .9])
colorbar.outline.set_visible(True)
plt.show()
Conclusion so far: The issue is not reproducible, at least not without a Minimal, Complete, and Verifiable example.
I'm uncertain about the reasons for the behaviour in the example from the question. However, it seems that it can be overcome by rounding the figure size to 3 significant digits
matplotlib.rcParams['figure.figsize'] = (5.25, np.round(figheight,3))

How to set a fixed/static size of circle marker on a scatter plot?

I want to plot the location of some disks generated randomly on a scatter plot, and see whether the disks are 'connected' to each other. For this, I need to set the radius of each disk fixed/linked to the axis scale.
The 's' parameter in the plt.scatter function uses points, so the size is not fixed relative to the axis. If I dynamically zoom into the plot, the scatter marker size remains constant on the plot and does not scale up with the axis.
How do I set the radius so they have a definite value (relative to the axis)?
Instead of using plt.scatter, I suggest using patches.Circle to draw the plot (similar to this answer). These patches remain fixed in size so that you can dynamically zoom in to check for 'connections':
import matplotlib.pyplot as plt
from matplotlib.patches import Circle # for simplified usage, import this patch
# set up some x,y coordinates and radii
x = [1.0, 2.0, 4.0]
y = [1.0, 2.0, 2.0]
r = [1/(2.0**0.5), 1/(2.0**0.5), 0.25]
fig = plt.figure()
# initialize axis, important: set the aspect ratio to equal
ax = fig.add_subplot(111, aspect='equal')
# define axis limits for all patches to show
ax.axis([min(x)-1., max(x)+1., min(y)-1., max(y)+1.])
# loop through all triplets of x-,y-coordinates and radius and
# plot a circle for each:
for x, y, r in zip(x, y, r):
ax.add_artist(Circle(xy=(x, y),
radius=r))
plt.show()
The plot this generates looks like this:
Using the zoom-option from the plot window, one can obtain such a plot:
This zoomed in version has kept the original circle size so the 'connection' can be seen.
If you want to change the circles to be transparent, patches.Circle takes an alpha as argument. Just make sure you insert it with the call to Circle not add_artist:
ax.add_artist(Circle(xy=(x, y),
radius=r,
alpha=0.5))

matplotlib polar plot scientific notation

I am trying to draw a polar plot with matplotlib and would like to do the following:
a) show tick labels with scientific notation
b) show radius circles at specified intervals.
Can anyone give me advice on how to do a) and b) with the code below
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111, polar=True)
theta =[np.pi/3, np.pi/3]
theta2 =[np.pi/6, np.pi/6]
r = [0.0, 8.0e-04]
r2 = [0.0, 7.0e-04]
ax.plot(theta, r, 'r-', label ='Observed')
ax.plot(theta2, r2, 'b-', label ='Simulated')
ax.grid(True)
ax.legend(loc='upper center', bbox_to_anchor=(0.5, 1.25),
ncol=3, fancybox=True, shadow=True)
plt.show()
For specifying location of radial ticks, it is very simple - you can just set rticks:
ax.set_rticks([0.0002, 0.0004, 0.0006, 0.0008])
There are a couple of options for the formatting, it depends on how exactly you want the ticks to be displayed. The default formatter will automatically switch to scientific for large and small numbers. If you want to change its threshold for what it considers "small", you can do that by modifying the yaxis formatter (the y axis is the radial axis):
ax.yaxis.get_major_formatter().set_powerlimits((-3,4)) # Things smaller than 1e-3
# will be in scientific
# notation
However, that looks a bit funny to me, it puts the little "1e-4" in the upper left of the plot.
So, if you want to force the current radial ticks to be scientific notation where they are, one way is to use your own format for them. The following uses FormatStrFormatter:
import matplotlib.ticker as ticker
# plotting code here
frmtr = ticker.FormatStrFormatter('%4.1e')
ax.yaxis.set_major_formatter(frmtr)
There are plenty of options available via matplotlib.ticker if this doesn't do exactly what you wanted. The second formatting option give me this:

Reducing the distance between two boxplots

I'm drawing the bloxplot shown below using python and matplotlib. Is there any way I can reduce the distance between the two boxplots on the X axis?
This is the code that I'm using to get the figure above:
import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['ytick.direction'] = 'out'
rcParams['xtick.direction'] = 'out'
fig = plt.figure()
xlabels = ["CG", "EG"]
ax = fig.add_subplot(111)
ax.boxplot([values_cg, values_eg])
ax.set_xticks(np.arange(len(xlabels))+1)
ax.set_xticklabels(xlabels, rotation=45, ha='right')
fig.subplots_adjust(bottom=0.3)
ylabels = yticks = np.linspace(0, 20, 5)
ax.set_yticks(yticks)
ax.set_yticklabels(ylabels)
ax.tick_params(axis='x', pad=10)
ax.tick_params(axis='y', pad=10)
plt.savefig(os.path.join(output_dir, "output.pdf"))
And this is an example closer to what I'd like to get visually (although I wouldn't mind if the boxplots were even a bit closer to each other):
You can either change the aspect ratio of plot or use the widths kwarg (doc) as such:
ax.boxplot([values_cg, values_eg], widths=1)
to make the boxes wider.
Try changing the aspect ratio using
ax.set_aspect(1.5) # or some other float
The larger then number, the narrower (and taller) the plot should be:
a circle will be stretched such that the height is num times the width. aspect=1 is the same as aspect=’equal’.
http://matplotlib.org/api/axes_api.html#matplotlib.axes.Axes.set_aspect
When your code writes:
ax.set_xticks(np.arange(len(xlabels))+1)
You're putting the first box plot on 0 and the second one on 1 (event though you change the tick labels afterwards), just like in the second, "wanted" example you gave they are set on 1,2,3.
So i think an alternative solution would be to play with the xticks position and the xlim of the plot.
for example using
ax.set_xlim(-1.5,2.5)
would place them closer.
positions : array-like, optional
Sets the positions of the boxes. The ticks and limits are automatically set to match the positions. Defaults to range(1, N+1) where N is the number of boxes to be drawn.
https://matplotlib.org/3.1.1/api/_as_gen/matplotlib.pyplot.boxplot.html
This should do the job!
As #Stevie mentioned, you can use the positions kwarg (doc) to manually set the x-coordinates of the boxes:
ax.boxplot([values_cg, values_eg], positions=[1, 1.3])