简体   繁体   中英

How to move specific x-axis (minor) tick labels to the top of a figure in matplotlib?

I want to keep the major tick labels, that matplotlib has automatically generated, in their default position under the figure. However, I myself added some minor ticks (with vertical lines) at specific x values, but their labels don't fit between the default major ticks. How can I move these labels to the top of the figure?

My code for reference:

meta = comparisons['meta']
lagsAnycast = np.array(meta['lagsAnycast'])
lagsPenultimate = np.array(meta['lagsPenultimate'])
avgLagAnycast = meta['avgLagAnycast']
avgLagPenultimate = meta['avgLagPenultimate']

plt.step(lagsAnycast, (np.arange(lagsAnycast.size) + 1)/lagsAnycast.size,  color='k', label='to anycast IPs', linewidth=1.5)
plt.step(lagsPenultimate, (np.arange(lagsPenultimate.size) + 1)/lagsPenultimate.size,  color='k', label='to penultimate IPs', linewidth=1)
plt.axvline(round(avgLagAnycast,1), ls="dashed", color="k", label="average lag to anycast IPs", linewidth=1.5)
plt.axvline(round(avgLagPenultimate,1), ls="dashed", label="average lag to penultimate IPs", color="k", linewidth=1)

plt.axis([-0.34,60,0.7,1])
plt.xlabel("Lag (ms)")
plt.ylabel("CDF")

existingTicks = (plt.xticks())[0][1:].tolist()
plt.gca().xaxis.grid(True, which='major')
plt.gca().xaxis.grid(False, which='minor')
plt.gca().tick_params(axis="x", which="minor", direction="out", top=True)
plt.gca().set_xticks([round(avgLagAnycast,1), round(avgLagPenultimate,1)], minor=True)

plt.legend(loc='right', fontsize=10)
plt.grid(True, ls="dotted")
majorFormatter = FormatStrFormatter('%g')
plt.gca().xaxis.set_major_formatter(majorFormatter)

plt.savefig(os.path.join(os.getcwd(), "datasets/plots/CDF1.png"))

You can use Locators and Formatters to set the ticks and ticklabels and turn them on or off using tick_params :

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

x = np.linspace(-3,3)
plt.plot(x, np.sin(x))

ticks = [-np.pi/2,np.pi/2.]
labels = [r"$-\frac{\pi}{2}$",r"$\frac{\pi}{2}$"]
ax = plt.gca()
ax.xaxis.set_minor_locator(ticker.FixedLocator(ticks))
ax.xaxis.set_minor_formatter(ticker.FixedFormatter(labels))

# Set visibility of ticks & tick labels
ax.tick_params(axis="x", which="minor", direction="out", 
                      top=True, labeltop=True, bottom=False, labelbottom=False)

plt.show()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM