【发布时间】:2016-10-24 12:45:11
【问题描述】:
我创建了一个子图网格,子图之间没有任何空格,共享 x,y 轴。我只显示外部子图的刻度和标签。问题是刻度数在子图的边界处重叠。使用 MaxNLocator,我可以删除上刻度或下刻度,但只能同时删除所有图。
问题:我怎样才能只为某些地块保留最高刻度(在这种情况下,x=2.0 仅在右下角的子图中,y=3 仅在左上角的子图中)?为什么我对某些子图的刻度条件设置失败?
代码:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator
numPlotsY = 3
numPlotsX = 3
f, ax_grid = plt.subplots(numPlotsY,numPlotsX,sharex=True,sharey=True)
A = np.arange(numPlotsY)+1.0
phi = np.arange(numPlotsX)
x = np.linspace(0,2.0,100)
fontsize = 18
for y_i in range(0,numPlotsY):
for x_i in range(0,numPlotsX):
y = A[y_i]*np.sin(x*np.pi + phi[x_i])
ax = ax_grid[y_i,x_i]
ax.plot(x,y,lw=2.0)
if x_i == 0:
ax.set_ylabel(r'$y$', fontsize=fontsize)
if y_i == numPlotsY-1:
###########################
# Why doesn't this work?! #
###########################
if x_i != numPlotsX-1:
nbins = len(ax.get_xticklabels())
ax.xaxis.set_major_locator(MaxNLocator(nbins=nbins,prune='upper'))
else:
nbins = len(ax.get_xticklabels())
ax.xaxis.set_major_locator(MaxNLocator(nbins=nbins,prune=None))
ax.set_xlabel(r'$x/\pi$', fontsize=fontsize)
if y_i == 0:
ax.set_title(r'$\phi=%s$' % phi[x_i], fontsize=fontsize)
if x_i == numPlotsX-1:
ax.annotate(r'$A=%d$' % A[x_i], xy=(1.1,0.5), rotation=90,
ha='center',va='center',xycoords='axes fraction', fontsize=fontsize)
f.subplots_adjust(wspace=0,hspace=0)
plt.suptitle(r'$A\cdot\sin\left(2\pi x + \phi\right)$',fontsize=18)
plt.show()
【问题讨论】:
-
This thread 说“由于轴是共享的,刻度标签也是共享的”,所以你所追求的可能是不可能的。请参阅密切相关的问答here。
标签: python matplotlib