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

pas*_*ash 20 python plot matplotlib

由于它们是在绘图区域内绘制的,因此许多matplotlib图中的数据会使轴刻度变得模糊.更好的方法是绘制从轴向延伸的刻度线,如ggplotR的绘图系统中的默认值.

从理论上讲,这可以通过重新绘制与所述刻度线来完成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()
Run Code Online (Sandbox Code Playgroud)

但实际上,这只是解决方案的一半,因为get_xticklinesget_yticklines方法只返回主要的滴答线.次要蜱仍指向内部.

小蜱的解决方法是什么?

Chr*_*isM 29

在你的matplotlib配置文件matplotlibrc中,你可以设置:

xtick.direction      : out     # direction: in or out
ytick.direction      : out     # direction: in or out
Run Code Online (Sandbox Code Playgroud)

这将默认向外绘制主要和次要刻度,如R.对于单个程序,只需执行:

>> from matplotlib import rcParams
>> rcParams['xtick.direction'] = 'out'
>> rcParams['ytick.direction'] = 'out'
Run Code Online (Sandbox Code Playgroud)