如何同时去除顶部和右侧坐标轴,并使刻度朝外?
我想用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()
1 个回答
8
稍微修改一下你的代码,并使用一个小技巧(或者说是个小窍门?)来自这个链接,这样似乎就能解决问题:
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()
如果你想让所有图表上的刻度线都朝外,可能更简单的方法是直接在配置文件中设置刻度线的方向。你可以在这个页面上找到相关信息,搜索xtick.direction
就可以了。