在 matplotlib 中将单位设置为 X 轴

4 python matplotlib

我使用此代码向轴添加单位,但 x 轴看起来很糟糕,数字和单位被覆盖。你知道如何解决它吗?

plt.gca().xaxis.set_major_formatter(FormatStrFormatter('%d cm'))
plt.gca().yaxis.set_major_formatter(FormatStrFormatter('%d cm'))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

Alv*_*tes 7

您需要旋转刻度的文本,试试这个:

import matplotlib.pyplot as plt
import matplotlib.ticker as mticker    

plt.plot(range(1000,11000,1000),range(10))

plt.gca().xaxis.set_major_formatter(mticker.FormatStrFormatter('%d cm'))
plt.gca().yaxis.set_major_formatter(mticker.FormatStrFormatter('%d cm'))

for txt in plt.gca().xaxis.get_majorticklabels():
    txt.set_rotation(90)

plt.tight_layout()
plt.show()
Run Code Online (Sandbox Code Playgroud)


小智 5

没有必要指定每个刻度中使用的单位,因为它在特定轴上都是相同的。我建议你使用xlabel()ylabel()方法,就像 matplotlib 文档中的这个例子一样:

http://matplotlib.org/examples/text_labels_and_annotations/text_demo_fontdict.html