【发布时间】:2016-03-17 15:07:40
【问题描述】:
如果绘图是对数的,如何删除绘图的第一个和最后一个刻度标签?
经典例子:
import matplotlib.pyplot as plt
import numpy as np
ax1 = plt.subplot(1, 3, 1)
x = np.logspace(-3,1,100)
plt.plot(x,np.random.random(size=100))
plt.xscale('log')
ax2 = plt.subplot(1, 3, 2, sharey = ax1)
plt.plot(x,np.random.random(size=100))
plt.tick_params(axis='y',labelleft='off')
plt.subplots_adjust(wspace=0)
导致 x 轴上的标签重叠。
现在,如果我通过*_ticklabels 做最直接的事情,例如,
l = [""] + [i.get_text() for i in ax2.get_xticklabels()[1:-1]] + [""]
ax2.set_xticklabels(l)
它不起作用(在脚本中,如果 matplotlib 先绘制绘图则不起作用)。
我发现的一种方法是使用自定义代码对象。例如
from matplotlib.ticker import ScalarFormatter
class _MyTickFormatter(ScalarFormatter):
def __init__(self, hide):
self.hide = hide
super(self.__class__, self).__init__()
def __call__(self, x, pos=None):
N = len(self.locs)
hide = [ N + i if i < 0 else i for i in self.hide ]
if pos in hide:
return ''
else:
return self.pprint_val(x)
有了这个就可以简单的做到ax2.set_major_formatter(_MyTickFormatter([0,-1]))。
但是,如果 x 轴是对数的(如上)。然后解决方案需要另一个自定义的 tickformatter...
另一种可能性是使用MaxNLocator,如in this answer by Bernie 所述。但是,在对数轴上使用它只会让我打勾(因为它应该使用LogLocator,我假设)。
有什么想法可以解决这个难题吗?
【问题讨论】:
标签: python matplotlib plot