我有一个 python matplotlib 图表,如下所示。
X 轴上有 100 多个项目,我确实想将它们全部绘制出来,但只需要大约 25 个(可能是自动的)以便看得清楚。
你能帮忙吗?
谢谢
我的代码也如下:
l1 = plt.plot(b)
plt.setp(l1, linewidth=4, color='r')
l2 = plt.plot(c)
plt.setp(l2, linewidth=4, color='k')
l3 = plt.plot(d)
plt.setp(l3, linewidth=4, color='g')
plt.xticks(range(len(a)), a)
plt.xticks(rotation=30)
plt.show()
plt.savefig('a.png')
注意:我还有表单中的数据列 a(X 轴变量)
u' 2016-02-29T00:01:30.000Z CHEPSTLC0007143 CDC-R114-DK'
抛出此错误 invalid literal for float()。这就是我使用 plt.xticks(range(len(a)), a) 的原因。
请您参考如下方法:
在这种情况下,mpl 完全按照您的指示执行操作,但您指示它执行的操作有点不方便。
plt.xticks(range(len(a)), a)
告诉 mpl 在每个整数处打勾,并使用 a 中的字符串来标记刻度(这是正确的做法)。我认为相反,你想做类似的事情
import matplotlib.pyplot as plt
import matplotlib.ticker as mticker
# synthetic data
a = list(range(45))
d = ['the label {}'.format(i) for i in range(45)]
# make figure + axes
fig, ax = plt.subplots(tight_layout=True)
ax.set_xlabel('x label')
ax.set_ylabel('y label')
# draw one line
ln1, = ax.plot(range(45), lw=4, color='r')
# helper function for the formatter
def listifed_formatter(x, pos=None):
try:
return d[int(x)]
except IndexError:
return ''
# make and use the formatter
mt = mticker.FuncFormatter(listifed_formatter)
ax.xaxis.set_major_formatter(mt)
# set the default ticker to only put ticks on the integers
loc = ax.xaxis.get_major_locator()
loc.set_params(integer=True)
# rotate the labels
[lab.set_rotation(30) for lab in ax.get_xticklabels()]
如果您平移/缩放,刻度标签将是正确的,并且 mpl 将选择一个合理数量的刻度来显示。
[旁注,此输出来自 2.x 分支并显示了一些新的默认样式]
