当x轴的值为字符串时,更改“滴答频率”

时间:2018-05-02 06:50:07

标签: python matplotlib

我有一个这样的清单:

x = ['alice', 'bob', ...] # len(x) > 100
y = [23, 323, ...] # just some number
plt.plot(x, y)
plt.show()

绘制时,它会显示x列表的每个值。有没有办法只显示像x[0], x[10], ...这样的值,但数字仍然相同。

我在网上找到的像Changing the "tick frequency" on x or y axis in matplotlib?这些都基于x轴的值都是int。当x轴的值是字符串时,我不确定该怎么做。

After rotate 90 degree

正如您所看到的,即使我将x轴标签旋转90度,它仍然很拥挤,所以我仍然需要找到一种方法来减少显示的x数。

3 个答案:

答案 0 :(得分:3)

如果我理解正确,请提及减少显示的刻度数。根据您的情节,有多种方法可以执行此操作,例如:

代码示例

import matplotlib.pyplot as plt
import numpy as np

x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
    14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
    25, 26, 27, 28, 29, 30, 31, 32]

y = [1, 4, 9, 6, 2, 4, 5, 6, 7, 2, 1, 
     4, 6, 5, 2, 3, 1, 4, 9, 6, 2, 4, 
     5, 6, 7, 2, 1, 4, 6, 5, 2, 3]

labels = ["Ant", "Bob", "Crab", "Donkey", "Elephant", "Fire", "Giant","Hello",
          "Igloo", "Jump", "Bull","Even", "More", "Words", "other", "Bazboo", 
          "Ant", "Bob", "Crab", "Donkey", "Hippo", "Fire", "Giant","Hello",
          "Igloo", "Hump", "Kellogg","Even", "More", "Words", "Piano", "Foobar"]

plt.xticks(x, labels[::2], rotation='vertical')
plt.locator_params(axis='x', nbins=len(x)/2)
plt.plot(x, y, 'g-', color='red')
plt.tight_layout(pad=4)
plt.subplots_adjust(bottom=0.15)
plt.show()

使用plt.locator_params和列表的长度可以将其分成两半,例如:

plt.xticks(x, labels[::2], rotation='vertical') # set divisor
plt.locator_params(axis='x', nbins=len(x)/2)  # set divisor 

plot 1

这应该显示一半的刻度数(x / 2),同时保持你的情节统一。这将对字符串和整数起作用,因为x的长度(len)在列表中起作用。

plt.xticks(x, labels, rotation='vertical')
plt.locator_params(axis='x', nbins=len(x))

plot 2

如果您想要更紧密的间距,请使用无除数或相应调整。

答案 1 :(得分:3)

您可以这样做的一种方法是减少x轴上的刻度数。您可以使用ax.set_xticks()设置滴答。在这里,您可以使用切片表示法x[::2]列表进行切片以在每个第2个条目处设置滴答。然后在设置刻度时使用相同的切片使用ax.set_xticklabels()设置x刻度标签。

例如:

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()

enter image description here

答案 2 :(得分:2)

如果x轴拥挤,我建议你另外一个解决方案:你可以用plt.xticks(rotation=45)旋转x值

enter image description here