【问题标题】:matplotlib not showing first label on x axis for the Bar Plotmatplotlib 未在条形图的 x 轴上显示第一个标签
【发布时间】:2017-09-26 04:27:49
【问题描述】:

这是我正在编写的用于创建对数条形图的代码

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

谢谢

【问题讨论】:

  • 这个问题在我的 matplotlib 1.5.3 上不存在,但在我刚升级到 2.0.0 后出现

标签: python matplotlib


【解决方案1】:

在 matplotlib 2.0 中,坐标轴边缘可能有未显示的刻度线。为了安全起见,除了刻度标签之外,您还可以设置刻度位置,

ax.set_xticks(np.arange(len(x)))
ax.set_xticklabels(x, rotation = 45)

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

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

【讨论】:

  • 现在有意义!
  • 我仍然不知道为什么,但这也对我有用。我以前使用过set_xticks(some_array_of_numbers),但它不起作用。不过,谢谢!
【解决方案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()

【讨论】:

    【解决方案3】:

    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)
    

    【讨论】:

      猜你喜欢
      • 2021-12-03
      • 2021-09-14
      • 1970-01-01
      • 2019-07-15
      • 2019-01-28
      • 1970-01-01
      • 2021-06-18
      • 2021-07-24
      • 1970-01-01
      相关资源
      最近更新 更多