In matplotlib, how do you draw R-style axis ticks pointing outward from the axes?

Since they are drawn inside the plot area, axis ticks are obscured by data in many matplotlib plots. The best approach is to draw ticks going from the axis outwards, as by default in ggplot , the R build system.

In theory, this can be done by redrawing the tick lines using the TICKDOWN and TICKLEFT for ticks of the x-axis and y-axis, respectively:

 import matplotlib.pyplot as plt import matplotlib.ticker as mplticker import matplotlib.lines as mpllines # Create everything, plot some data stored in `x` and `y` fig = plt.figure() ax = fig.gca() plt.plot(x, y) # Set position and labels of major and minor ticks on the y-axis # Ignore the details: the point is that there are both major and minor ticks ax.yaxis.set_major_locator(mplticker.MultipleLocator(1.0)) ax.yaxis.set_minor_locator(mplticker.MultipleLocator(0.5)) ax.xaxis.set_major_locator(mplticker.MultipleLocator(1.0)) ax.xaxis.set_minor_locator(mplticker.MultipleLocator(0.5)) # Try to set the tick markers to extend outward from the axes, R-style for line in ax.get_xticklines(): line.set_marker(mpllines.TICKDOWN) for line in ax.get_yticklines(): line.set_marker(mpllines.TICKLEFT) # In real life, we would now move the tick labels farther from the axes so our # outward-facing ticks don't cover them up plt.show() 

But in practice, this is only half the solution, because the get_xticklines and get_yticklines return only the main tick lines. Small ticks continue to point inward.

What work for minor ticks?

+19
python matplotlib plot
Jun 07 2018-11-11T00:
source share
2 answers

In your matplotlib config file, matplotlibrc, you can set:

 xtick.direction : out # direction: in or out ytick.direction : out # direction: in or out 

and by default it will be both main and minor ticks, for example R. For one program, just do:

 >> from matplotlib import rcParams >> rcParams['xtick.direction'] = 'out' >> rcParams['ytick.direction'] = 'out' 
+28
Mar 25 2018-12-25T00:
source share

You can get minors in at least two ways:

 >>> ax.xaxis.get_ticklines() # the majors <a list of 20 Line2D ticklines objects> >>> ax.xaxis.get_ticklines(minor=True) # the minors <a list of 38 Line2D ticklines objects> >>> ax.xaxis.get_minorticklines() <a list of 38 Line2D ticklines objects> 

Please note that 38 is that small tick lines were also displayed in β€œlarge” places when calling MultipleLocator.

+4
Jun 07 2018-11-11T00:
source share



All Articles