以下是我正在编写的用于创建对数条形图的代码
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
。这是我得到的情节那么如何纠正呢? Matplotlib版本为2.0.0
,Numpy版本为1.12.1
由于
答案 0 :(得分:13)
在matplotlib 2.0中,轴的边缘可能有未示出的刻度线。为了安全起见,除了刻度标签外,您还可以设置刻度线位置
ax.set_xticks(np.arange(len(x)))
ax.set_xticklabels(x, rotation = 45)
如果标签旋转,您可能还需要将标签设置为与其右边缘对齐:
ax.set_xticklabels(x, rotation = 45, ha="right")
答案 1 :(得分:2)
是的,同意这有点奇怪。无论如何,这里有一个方法(只是在之前定义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()
答案 2 :(得分:1)
set_xticklabels()将设置显示的文本refer to this。 所以这样修改应该有效:
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)