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

2024-05-23 19:03:49 发布

您现在位置:Python中文网/ 问答频道 /正文

由于轴记号是在绘图区域内绘制的,因此在许多matplotlib绘图中,轴记号会被数据遮挡。更好的方法是绘制从轴向外延伸的刻度,这是R的绘图系统ggplot中的默认值。

理论上,这可以通过分别使用x轴和y轴刻度的TICKDOWNTICKLEFT线样式重新绘制刻度线来完成:

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方法只返回major刻度线。小记号仍指向内部。

小虱子怎么办?


Tags: andthegetmatplotliblinepltaxset
2条回答

您至少可以通过两种方式获取未成年人:

>>> 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是因为multipleocator调用也在“major”位置绘制了小刻度线。

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

相关问题 更多 >