简体   繁体   English

Matplotlib:如何在图上方设置刻度线标签

[英]Matplotlib: how to set a tick label above a plot

不好
This is the sine and cosine plot I draw using matplotlib. 这是我使用matplotlib绘制的正弦和余弦图。 But the tick labels are below the plot and can hardly seen. 但是刻度线标签位于图的下方,几乎看不到。

My python code is: 我的python代码是:

import numpy as np
import matplotlib.pyplot as plt

fig = plt.figure(figsize=(8,6), dpi=96)
plt.subplot(111)

X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C,S = np.cos(X), np.sin(X)

plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-", label="consine")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-", label="sine")

plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)

plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],
          [r'$-\pi$', r'$-\frac{\pi}{2}$', r'$0$', r'$+\frac{\pi}{2}$', r'$+\pi$'])
plt.yticks([-1,  1],
          [r'$-1$', r'$+1$'])

ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

plt.legend(loc='upper left', frameon=False)


for label in ax.get_xticklabels()+ax.get_yticklabels():
    label.set_fontsize(16)
    label.set_bbox(dict(facecolor='green', edgecolor='None', alpha=0.2))


plt.savefig("figures/exercise10.png", dpi=120)
plt.show()

So, how should I set a tick label above a plot? 那么,如何在情节上方设置刻度线标签?

理想效果

Thank you! 谢谢!

Possibly you want to set the labels and the axes spines on top of the lines. 可能您想设置标签,并且将轴尖刺在线条的顶部。 This can easily be achieved with the "axes.axisbelow" rcParam. 使用"axes.axisbelow" rcParam可以轻松实现。

plt.rcParams["axes.axisbelow"] = False

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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