Matplotlib在柱状图的x轴上没有显示第一个标签。

21
这是我正在使用的代码,用于创建对数条形图。
import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize = (12,6))

ax = fig.add_subplot(111)

x = ['Blue Whale', 'Killer Whale', 'Bluefin tuna', \
     'Bottlenose dolphin', "Maui's dolphin", 'Flounder',\
     'Starfish', 'Spongebob Squarepants']

y = [190000, 5987, 684, 650, 40, 6.8, 5, 0.02]

ax.bar(np.arange(len(x)),y, log=1)

ax.set_xticklabels(x, rotation = 45)


fig.savefig(filename = "f:/plot.png")
现在正在创建条形图,但它没有显示第一个标签,即Blue Whale。这是我得到的图enter image description here。那么这怎么办呢?Matplotlib版本为2.0.0,Numpy版本为1.12.1

谢谢


这个问题在我的matplotlib 1.5.3上没有出现,但是在我刚升级到2.0.0后出现了。 - Martin Evans
3个回答

32
在matplotlib 2.0中,轴边缘可能存在未显示的刻度标记。为确保安全起见,可以设置刻度位置以及刻度标签。
ax.set_xticks(np.arange(len(x)))
ax.set_xticklabels(x, rotation = 45)

如果标签被旋转了,您可能还希望将标签设置为与其右边缘对齐:

ax.set_xticklabels(x, rotation = 45, ha="right")

现在懂了吗! - user9026
我仍然不知道为什么,但这对我也起作用了。我之前使用了 set_xticks(some_array_of_numbers) 但它没有起作用。谢谢你! - pookie

3

没错,我也觉得这有点奇怪。不过,有一个解决方法(先定义 xticks 即可)。

import matplotlib.pyplot as plt
import numpy as np

x = ['Blue Whale', 'Killer Whale', 'Bluefin tuna', \
     'Bottlenose dolphin', "Maui's dolphin", 'Flounder',\
     'Starfish', 'Spongebob Squarepants']

y = [190000, 5987, 684, 650, 40, 6.8, 5, 0.02]


fig = plt.figure(figsize = (12,6))
ax = fig.add_subplot(111)
ax.bar(np.arange(len(x)),y, log=1)
ax.set_xticks(np.arange(len(x)))
ax.set_xticklabels(x, rotation = 45, zorder=100)
fig.show()

enter image description here


1

set_xticklabels()函数将设置显示的文本参考此处。 因此,修改如下应该可以工作:

import matplotlib.pyplot as plt
import numpy as np

fig = plt.figure(figsize = (12,6))

ax = fig.add_subplot(111)

x = ['Blue Whale', 'Killer Whale', 'Bluefin tuna', \
 'Bottlenose dolphin', "Maui's dolphin", 'Flounder',\
 'Starfish', 'Spongebob Squarepants']

y = [190000, 5987, 684, 650, 40, 6.8, 5, 0.02]

pos = np.arange(len(x))
ax.bar(pos,y, log=1)
ax.set_xticks(pos)
ax.set_xticklabels(x, rotation = 45)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接