【问题标题】:Barplot with log y-axis program syntax with matplotlib pyplot带有 log y 轴程序语法的条形图与 matplotlib pyplot
【发布时间】:2013-08-04 03:10:08
【问题描述】:

我意识到这个问题之前已经被问过(Python Pyplot Bar Plot bars disappear when using log scale),但给出的答案对我不起作用。我设置了我的 pyplot.bar(x_values, y_values, etc, log = True) 但收到一条错误消息:

"TypeError: unsupported operand type(s) for +: 'NoneType' and 'int'"

我一直在寻找 pyplot 代码的实际示例,该示例使用 y 轴设置为记录的条形图,但没有找到。我做错了什么?

代码如下:

import matplotlib.pyplot as pyplot
ax = fig.add_subplot(111)
fig = pyplot.figure()
x_axis = [0, 1, 2, 3, 4, 5]
y_axis = [334, 350, 385, 40000.0, 167000.0, 1590000.0]
ax.bar(x_axis, y_axis, log = 1)
pyplot.show()

即使我删除了 pyplot.show,我也会收到错误消息。提前感谢您的帮助

【问题讨论】:

  • 请显示使用完整回溯

标签: python matplotlib typeerror bar-chart


【解决方案1】:

您确定这就是您的所有代码吗?代码在哪里抛出错误?在绘图期间?因为这对我有用:

In [16]: import numpy as np
In [17]: x = np.arange(1,8, 1)
In [18]: y = np.exp(x)

In [20]: import matplotlib.pyplot as plt
In [21]: fig = plt.figure()
In [22]: ax = fig.add_subplot(111)
In [24]: ax.bar(x, y, log=1)
Out[24]: 
[<matplotlib.patches.Rectangle object at 0x3cb1550>,
 <matplotlib.patches.Rectangle object at 0x40598d0>,
 <matplotlib.patches.Rectangle object at 0x4059d10>,
 <matplotlib.patches.Rectangle object at 0x40681d0>,
 <matplotlib.patches.Rectangle object at 0x4068650>,
 <matplotlib.patches.Rectangle object at 0x4068ad0>,
 <matplotlib.patches.Rectangle object at 0x4068f50>]
In [25]: plt.show()

这是剧情

【讨论】:

  • 代码在到达 ax.bar(x, y, log=1) 时抛出错误。由于某种原因,它仍然无法正常工作
【解决方案2】:

正如 cmets 对 Greg 的回答所建议的那样,通过将默认行为设置为“clip”,您确实看到了 fixed in matplotlib 1.3 的问题。升级到 1.3 为我解决了这个问题。

请注意,无论是作为bar 的关键字参数,还是通过轴上的set_yscale,应用对数刻度的方式似乎并不重要。

另请参阅建议此解决方法的 this answer to "Logarithmic y-axis bins in python"

plt.yscale('log', nonposy='clip')

【讨论】:

    【解决方案3】:

    由于ax.bar(... 中的log = True 语句而引发错误。我不确定这是 matplotlib 错误还是以非预期的方式使用。它可以通过删除有问题的参数log=True 轻松修复。

    这可以通过简单地自己记录 y 值来解决。

    x_values = np.arange(1,8, 1)
    y_values = np.exp(x_values)
    
    log_y_values = np.log(y_values)
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.bar(x_values,log_y_values) #Insert log=True argument to reproduce error
    

    需要添加适当的标签log(y) 以明确它是日志值。

    【讨论】:

    • 问题是我设置y_axis为log的时候条没有填写
    • 我已经在编辑中解决了这些问题。我承认它不如记录 x 轴漂亮,但错误来自 log=True 参数仍然是正确的。
    • 我想我可以手动设置轴标签 - 这可以作为一个止损,但我仍然对为什么 log=True 给我错误感到困惑。
    • 贾斯汀这一定是 matplotlib 的一个错误,我刚刚在我的工作计算机上用 matplotlib 1.3 重试了这个,log=True 工作正常。你用的是什么版本,或许值得installing 1.3
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 2014-06-06
    • 1970-01-01
    • 1970-01-01
    • 2019-01-23
    • 1970-01-01
    相关资源
    最近更新 更多