我想制作一个仅包含左轴和下轴的matplotlib图,以及面向外而不是向内的刻度作为默认值。我发现了两个分别针对这两个主题的问题:
他们每个人都独立工作,但不幸的是,这两种解决方案似乎彼此不相容。在敲了一下头之后,我在the axes_grid
documentation中发现了一个警告
“某些命令(主要与刻度相关)不起作用”
这是我的代码:
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()
答案 0 :(得分:7)
稍微改变你的代码,并使用来自this link的技巧(或黑客?),这似乎有效:
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()
如果您想在所有图表上向外勾选,可能更容易设置勾选方向in the rc file - 在该页面上搜索xtick.direction