我想制作一个只有左轴和下轴的matplotlib图,默认情况下还有朝外而不是向内的记号。我发现了两个分别涉及这两个主题的问题:
-
在matplotlib中,如何绘制从轴向外指向的R样式轴记号?
-
如何删除matplotlib中的顶部和右侧轴?
它们各自独立工作,但不幸的是,这两种解决方案似乎互不兼容。经过一段时间的思考,我在axes_grid
文档中发现了一条警告,上面写着
"一些命令(主要与勾号相关)不起作用"
这是我的代码:
from matplotlib.pyplot import *
from mpl_toolkits.axes_grid.axislines import Subplot
import matplotlib.lines as mpllines
import numpy as np
#set figure and axis
fig = figure(figsize=(6, 4))
#comment the next 2 lines to not hide top and right axis
ax = Subplot(fig, 111)
fig.add_subplot(ax)
#uncomment next 2 lines to deal with ticks
#ax = fig.add_subplot(111)
#calculate data
x = np.arange(0.8,2.501,0.001)
y = 4*((1/x)**12 - (1/x)**6)
#plot
ax.plot(x,y)
#do not display top and right axes
#comment to deal with ticks
ax.axis["right"].set_visible(False)
ax.axis["top"].set_visible(False)
#put ticks facing outwards
#does not work when Sublot is called!
for l in ax.get_xticklines():
l.set_marker(mpllines.TICKDOWN)
for l in ax.get_yticklines():
l.set_marker(mpllines.TICKLEFT)
#done
show()
稍微更改您的代码,并使用此链接中的技巧(或破解?),这似乎有效:
import numpy as np
import matplotlib.pyplot as plt
#comment the next 2 lines to not hide top and right axis
fig = plt.figure()
ax = fig.add_subplot(111)
#uncomment next 2 lines to deal with ticks
#ax = fig.add_subplot(111)
#calculate data
x = np.arange(0.8,2.501,0.001)
y = 4*((1/x)**12 - (1/x)**6)
#plot
ax.plot(x,y)
#do not display top and right axes
#comment to deal with ticks
ax.spines["right"].set_visible(False)
ax.spines["top"].set_visible(False)
## the original answer:
## see http://old.nabble.com/Ticks-direction-td30107742.html
#for tick in ax.xaxis.majorTicks:
# tick._apply_params(tickdir="out")
# the OP way (better):
ax.tick_params(axis='both', direction='out')
ax.get_xaxis().tick_bottom() # remove unneeded ticks
ax.get_yaxis().tick_left()
plt.show()
如果你想在所有的绘图上向外打勾,在rc文件中设置勾号方向可能会更容易——在该页面上搜索xtick.direction