如何让 x 轴标签适合图形的宽度?
How to get the x axis labels to fit the width of the graph?
这是我的代码:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.canvas.draw()
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = 'Inbox'
labels[1] = 'Sent'
labels[2] = 'Important'
labels[3] = 'Starred'
labels[4] = 'Unread'
ax.set_xticklabels(labels)
plt.plot([1500,1200,900,600,300])
plt.show()
如您所见,我只想要 x 轴上的 5 个标签。然而,当我 运行 图形时,它会为标签生成 8 个可用插槽。前 5 个是我想要的标签,但最后 3 个是空白的。如何只设置我想要的 5 个标签?
这是因为绘图不仅会为您指定的点绘制点,还会绘制其他点。如果不更改轴标签,问题很明显:
如果你想为你的数据设置 5 个刻度,那么你还需要设置它们的位置,使用 set_xticks()
- 如果你不这样做,那么你只需替换已经存在的刻度的刻度标签存在,这不是你想要的。
但这不是重点,这种数据不应该用这样的线表示,应该用条形图:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x_locs = np.arange(5)
width = 0.9
email_labels = ["Inbox", "Sent", "Important", "Starred", "Unread"]
email_volumes = [1500, 1200, 900, 600, 300]
ax.bar(x_locs-width/2.0, email_volumes, width)
ax.set_xticks(x_locs)
ax.set_xticklabels(email_labels)
plt.show()
这是我的代码:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.canvas.draw()
labels = [item.get_text() for item in ax.get_xticklabels()]
labels[0] = 'Inbox'
labels[1] = 'Sent'
labels[2] = 'Important'
labels[3] = 'Starred'
labels[4] = 'Unread'
ax.set_xticklabels(labels)
plt.plot([1500,1200,900,600,300])
plt.show()
如您所见,我只想要 x 轴上的 5 个标签。然而,当我 运行 图形时,它会为标签生成 8 个可用插槽。前 5 个是我想要的标签,但最后 3 个是空白的。如何只设置我想要的 5 个标签?
这是因为绘图不仅会为您指定的点绘制点,还会绘制其他点。如果不更改轴标签,问题很明显:
如果你想为你的数据设置 5 个刻度,那么你还需要设置它们的位置,使用 set_xticks()
- 如果你不这样做,那么你只需替换已经存在的刻度的刻度标签存在,这不是你想要的。
但这不是重点,这种数据不应该用这样的线表示,应该用条形图:
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots()
x_locs = np.arange(5)
width = 0.9
email_labels = ["Inbox", "Sent", "Important", "Starred", "Unread"]
email_volumes = [1500, 1200, 900, 600, 300]
ax.bar(x_locs-width/2.0, email_volumes, width)
ax.set_xticks(x_locs)
ax.set_xticklabels(email_labels)
plt.show()