本文介绍了删除matplotlib中子图上的重叠刻度线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用以下函数创建了以下子图集:
I've create the following set of subplots using the following function:
def create31fig(size,xlabel,ylabel,title=None):
fig = plt.figure(figsize=(size,size))
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)
plt.subplots_adjust(hspace=0.001)
plt.subplots_adjust(wspace=0.001)
ax1.set_xticklabels([])
ax2.set_xticklabels([])
xticklabels = ax1.get_xticklabels()+ ax2.get_xticklabels()
plt.setp(xticklabels, visible=False)
ax1.set_title(title)
ax2.set_ylabel(ylabel)
ax3.set_xlabel(xlabel)
return ax1,ax2,ax3
如何确保子图(312)的顶部和底部与相邻区域不重叠?谢谢.
How do I make sure the top and bottom of subplot(312) do not overlap with their neighbours? Thanks.
推荐答案
在置顶模块中有一个名为 MaxNLocator 可以修剪梅花肉.
使用它可以删除第二个和第三个子图的最上面的刻度:
In the ticker module there is a class called MaxNLocator that can take a prune kwarg.
Using that you can remove the topmost tick of the 2nd and 3rd subplots:
import matplotlib.pyplot as plt
from matplotlib.ticker import MaxNLocator # added
def create31fig(size,xlabel,ylabel,title=None):
fig = plt.figure(figsize=(size,size))
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)
plt.subplots_adjust(hspace=0.001)
plt.subplots_adjust(wspace=0.001)
ax1.set_xticklabels([])
ax2.set_xticklabels([])
xticklabels = ax1.get_xticklabels() + ax2.get_xticklabels()
plt.setp(xticklabels, visible=False)
ax1.set_title(title)
nbins = len(ax1.get_xticklabels()) # added
ax2.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='upper')) # added
ax2.set_ylabel(ylabel)
ax3.yaxis.set_major_locator(MaxNLocator(nbins=nbins,prune='upper')) # added
ax3.set_xlabel(xlabel)
return ax1,ax2,ax3
create31fig(5,'xlabel','ylabel',title='test')
在进行这些调整后对图像进行采样:
Sample image after making those adjustments:
另外:如果最低子图中重叠的 x 和 y 标签是一个问题,请考虑修剪"其中之一.
Aside: If the overlapping x- and y- labels in the lowest subplot are an issue consider "pruning" one of those as well.
这篇关于删除matplotlib中子图上的重叠刻度线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!