如何调整字符串 x 轴的“滴答频率"? [英] How to adjust 'tick frequency' for string x-axis?
问题描述
我有一个清单要画.有没有办法显示x轴标签的一部分,例如 x [0],x [10],...
,但保持图形不变?
x = ['alice', 'bob', ...] # 字符串列表,len >100y = [23,323,...]#整数列表plt.plot(x, y)plt.show()
还有其他一些问题,例如
I have a list to draw. Is there a way to display parts of x-axis labels, for example x[0], x[10], ...
, but keep the figure the same?
x = ['alice', 'bob', ...] # string list, len > 100
y = [23, 323, ...] # int list
plt.plot(x, y)
plt.show()
Edit 1: There are some other questions like Changing the "tick frequency" on x or y axis in matplotlib? dealing with int label. But doesn't work for me.
Edit 2: Rotating x-axis labels can not help.
One way you can do this is to reduce the number of ticks on the x axis. You can set the ticks using ax.set_xticks()
. Here you can slice the x
list to set a ticks at every 2nd entry using the slice notation [::2]
. Then set the x tick labels using ax.set_xticklabels()
using the same slice when setting the ticks.
For example:
x = ["Ant", "Bob", "Crab", "Donkey", "Elephant", "Fire", "Giant","Hello",
"Igloo", "Jump", "Kellogg","Llama", "More", "Night"]
y = np.random.randint(0,10,14)
fig, (ax1, ax2) = plt.subplots(1,2, figsize=(9,5))
ax1.plot(x,y)
ax1.set_title("Crowded x axis")
ax2.plot(x,y)
ax2.set_xticks(x[::2])
ax2.set_xticklabels(x[::2], rotation=45)
ax2.set_title("Every 2nd ticks on x axis")
plt.show()
这篇关于如何调整字符串 x 轴的“滴答频率"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!