Because they are drawn inside the plot area, axis ticks are obscured by the data in many matplotlib plots. A better approach is to draw the ticks extending from the axes outward, as is the default in ggplot
, R's plotting system.
In theory, this can be done by redrawing the tick lines with the TICKDOWN
and TICKLEFT
line-styles for the x-axis and y-axis ticks 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, that's only half the solution because the get_xticklines
and get_yticklines
methods return only the major tick lines. The minor ticks remain pointing inward.
What's the work-around for the minor ticks?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…