Tags matplotlib prune tick

I use GridSpec to plot two graphs one below the other without a gap between them with

gs = gridspec.GridSpec(3, 1) gs.update(hspace=0., wspace=0.) ax1 = plt.subplot(gs[0:2, 0]) ax2 = plt.subplot(gs[2, 0], sharex=ax1) 

which works great. However, I want to get rid of every label on the top and bottom subtitles. For this I use

 nbins = len(ax1.get_yticklabels()) ax1.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='both')) nbins = len(ax2.get_yticklabels()) ax2.yaxis.set_major_locator(MaxNLocator(nbins=nbins, prune='both')) 

which in many cases works fine. However, in some scenes there is still one or more of the four cropping shortcuts. I looked, for example. ax1.get_ylim() and noticed that instead of, for example, the upper limit was 10 (as shown in the plot itself), this is actually 10.000000000000002 , which, I suspect, is the reason why it is not trimmed. How does this happen and how can I get rid of this?

Here is an example: Notice that in the figure the y axis is inverted and no label is cropped, although it should be. Also note that for some reason, the lowest y-tag is set to a negative position that I don't see. The y-tick positions are displayed in the axis coordinates in the text inside the graphs. In the image below, the mark in 10.6 should not be!

 import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec from matplotlib.ticker import MaxNLocator import numpy as np x1 = 1 y1 = 10.53839 err1 = 0.00865 x2 = 2 y2 = 9.43045 err2 = 0.00658 plt.clf() fig = plt.figure(figsize=(6, 6)) gs = gridspec.GridSpec(3, 1) gs.update(hspace=0., wspace=0.) ax1 = plt.subplot(gs[0:2, 0]) ax1.errorbar(x1, y1, yerr=err1) ax1.errorbar(x2, y2, yerr=err2) ax1.invert_yaxis() plt.setp(ax1.get_xticklabels(), visible=False) # Remove x-labels between the plots plt.xlim(0, 3) ax2 = plt.subplot(gs[2, 0], sharex=ax1) nbins = len(ax1.get_yticklabels()) ax1.yaxis.set_major_locator(MaxNLocator(nbins=8, prune='both')) nbins = len(ax2.get_yticklabels()) ax2.yaxis.set_major_locator(MaxNLocator(nbins=6, prune='both')) plt.savefig('prune.png') plt.close() 

prune

+6
source share
1 answer

Could it be that you are looking at the largest mark on the x axis of the top section? If so, this should do the trick:

 ax1.set_xticklabels([]) 

EDIT . If you use sharex , you must use this, otherwise the label marks will be deleted on both axes.

 plt.setp(ax1.get_xticklabels(), visible=False) 
+2
source

Source: https://habr.com/ru/post/980889/


All Articles