Markers on plot edges cut off in matplotlib


Question

I want to make a scatter plot using matplotlib. If I want to use any kind of marker the default plotting behavior of matplotlib cuts off the left half of the marker on the left side of the plot, and the right side of the marker on the right side of the plot. I was looking for the most automatic way of adding some extra space to the left and right side of the plot without adding extra tick labels, so my markers aren't cut off and it also doesn't look like there are x-tick labels that don't correspond to any points.

from matplotlib import pyplot as plt
import numpy as np
xx = np.arange(10)
yy = np.random.random( 10 )
plt.plot(xx, yy, 'o' )

This code results in a graph that looks like this:

enter image description here

I'd like full circles at x = 0 and x = 4.5, but I don't want any more tick labels, and I'd like to be the code to be as short and automatic as possible.

1
15
2/24/2012 3:25:17 PM

Accepted Answer

You will have to write some code to do this, but you wont need to know anything about your data in advance. In other words, xx can change and this still will work as you expect (I think).

Basically you'd like the x-tick labels that you have, but you don't like the limits. So write code to

  1. save the ticks,
  2. adjust the limits, and
  3. reinstate the old ticks.

from matplotlib import pyplot as plt
import numpy as np
xx = np.arange(10)
np.random.seed(101)
yy = np.random.random( 10 )
plt.plot(xx, yy, 'o' )
xticks, xticklabels = plt.xticks()
# shift half a step to the left
# x0 - (x1 - x0) / 2 = (3 * x0 - x1) / 2
xmin = (3*xticks[0] - xticks[1])/2.
# shaft half a step to the right
xmax = (3*xticks[-1] - xticks[-2])/2.
plt.xlim(xmin, xmax)
plt.xticks(xticks)
plt.show()

This results in the following figure: enter image description here

As you can see, you have the same issue for the y values, which you can correct following the same procedure.


Another option is turning off the clipping of the line, using the clip_on keyword: plt.plot(xx, yy, 'o', clip_on=False):

enter image description here

Now the circles are right at the edge, but they are not clipped and extend past the frame of the axes.

31
3/14/2012 1:46:54 AM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon