在matplotlib中,如何绘制指向外部的R风格坐标轴刻度?

21 投票
2 回答
7598 浏览
提问于 2025-04-16 19:05

在很多使用matplotlib绘图的情况下,数据会挡住坐标轴上的刻度线,因为这些刻度线是在绘图区域内部绘制的。一个更好的方法是让刻度线从坐标轴向外延伸,这样的效果在R语言的绘图系统ggplot中是默认的。

理论上,我们可以通过重新绘制刻度线来实现这个效果,分别使用TICKDOWNTICKLEFT样式来处理x轴和y轴的刻度线:

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()

但是在实际操作中,这只是解决方案的一半,因为get_xticklinesget_yticklines方法只返回了主要刻度线,而次要刻度线仍然是指向内部的。

那么,次要刻度线该怎么处理呢?

2 个回答

4

你可以通过至少两种方式来获取次要刻度:

>>> 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>

注意,这里的38是因为在“主要”位置也画了次要刻度线,这是通过MultipleLocator这个调用实现的。

29

在你的 matplotlib 配置文件,也就是 matplotlibrc 里,你可以设置:

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

这样设置后,默认情况下会把主要和次要的刻度线都向外画,就像 R 语言那样。如果你只想在一个程序里这样做,可以直接使用:

>> from matplotlib import rcParams
>> rcParams['xtick.direction'] = 'out'
>> rcParams['ytick.direction'] = 'out'

撰写回答