如何将特定的x轴(次要)刻度标签移动到matplotlib中图形的顶部?

时间:2017-06-21 15:22:46

标签: python matplotlib

我希望将matplotlib自动生成的主要刻度标签保留在图下的默认位置。但是,我自己在特定的x值处添加了一些小的刻度(带有垂直线),但是它们的标签不适合默认的主要刻度。如何将这些标签移到图的顶部?

我的参考代码:

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"))

1 个答案:

答案 0 :(得分:3)

您可以使用定位器和格式化程序设置刻度线和刻度标签,并使用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))
plt.gca().tick_params(axis="x", which="minor", direction="out", 
                       top=1, bottom=0, labelbottom=0, labeltop=1)

plt.show()

enter image description here