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

发布于 2021-01-29 16:31:05

因为它们是在绘图区域内绘制的,所以许多matplotlib绘图中的数据掩盖了轴刻度。更好的方法是绘制从轴向
延伸的刻度线,这是ggplotR的绘图系统中的默认设置。

从理论上讲,可以通过分别用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_xticklinesandget_yticklines方法仅返回 主要的
刻度线。小刻度线仍然指向内。

小滴答的解决方法是什么?

关注者
0
被浏览
50
1 个回答
  • 面试哥
    面试哥 2021-01-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'
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看