【问题标题】:Matplotlib Xticklabels not workingMatplotlib Xticklabels 不工作
【发布时间】:2011-09-14 13:32:39
【问题描述】:

1. X-ticklabels 不起作用

我正在使用 Matplotlib 从一些测量中生成直方图:

import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pyplot
...
fig = pyplot.figure()
ax = fig.add_subplot(1,1,1,)
n, bins, patches = ax.hist(measurements, bins=50, range=(graph_minimum, graph_maximum), histtype='bar')

ax.set_xticklabels([n], rotation='vertical')


for patch in patches:
    patch.set_facecolor('r')

pyplot.title='Foobar'
#pyplot.grid(True)
pyplot.xlabel('X-Axis')
pyplot.ylabel('Y-Axis')
pyplot.savefig(output_filename)

生成的 PNG 看起来不错,除了两个问题:

  1. PNG 中缺少标题(“Spam and Ham”)。 x 和 y 轴标签都存在(尽管我没有为下面的示例打开它们)。
  2. x-tick-lables 似乎完全损坏了 - 它没有显示在所有条形下方的底部,而是呈现为图形左下方下方的单行数字,被截断。它似乎也禁用了我的 Y 轴标签。

2。单位和 SI 前缀

注意:不是 Matplotlib 特定的。

直方图沿 x 轴具有时间测量值。这些范围从微秒范围到毫秒和秒范围。目前,该图将 x 轴标签呈现为标准表示法中的秒数。

我想要友好的格式我宁愿时间以毫秒/微秒的值给出,并显示单位。所以这意味着我想要一些东西来友好地格式化时间值,并注意 SI 前缀。

实际上,它可能与这里的示例程序非常相似:

http://diveintopython3.org/your-first-python-program.html

我确实注意到有一些 Python 库可以处理单元:

  1. http://juanreyero.com/open/magnitude/index.html
  2. http://home.scarlet.be/be052320/Unum.html
  3. http://pypi.python.org/pypi/units/

但是,根据我的阅读,上面的任何处理 SI 前缀似乎都没有,也没有进行这种友好的格式化。有什么建议/替代方案吗?

【问题讨论】:

    标签: python matplotlib histogram graphing


    【解决方案1】:

    1.1:PNG 中缺少标题(“Spam and Ham”)。

    你写的

    pyplot.title='Foobar'
    

    你想要

    pyplot.title("Spam and Ham")
    

    pyplot.title='Foobar' 只是简单地将标题函数替换为字符串。

    1.2:x-tick-lables 似乎完全损坏了

    ISTM ax.set_xticklabels([n], rotation='vertical') 可能不是您想要做的,因为我不认为 n 是您认为的那样。对于测量 [1,2,3,4],我们得到:

    >>> n, bins, patches = ax.hist([1,2,3,4])
    >>> n
    array([1, 0, 0, 1, 0, 0, 1, 0, 0, 1])
    >>> bins
    array([ 1. ,  1.3,  1.6,  1.9,  2.2,  2.5,  2.8,  3.1,  3.4,  3.7,  4. ])
    >>> patches
    <a list of 10 Patch objects>
    

    n 是一个数组,包含 bin 中的计数,而不是 bin 位置;是y轴,不是x。此外,它已经是一个列表,因此无论如何都不需要使用 [n] 。我不确定你想做什么,但你可以从垃圾箱制作字符串标签(除非你想要很多数字!)或者,如果你只希望 xtick 标签是垂直的,你可以使用

    for label in ax.get_xticklabels():
        label.set_rotation('vertical')
    

    恐怕我对单元库一无所知。

    【讨论】:

    • 帝斯曼:感谢您的帮助。是的,标题问题解决了 - 愚蠢,应该阅读文档 =)。我设法将 n 数组“n”转换为一个列表,它有点工作,但不是真的。但你是对的,这不是我想要的。无论如何,我已经给了你这个答案=)。我将更具体地重新提出这个问题,只针对 xtick 问题 - stackoverflow.com/questions/6352740/matplotlib-label-each-bin
    【解决方案2】:

    要将 SI 前缀添加到您要使用的轴标签,请使用 QuantiPhy。事实上,在其文档中,它有一个示例说明了如何执行此操作:MatPlotLib Example

    我想你会在你的代码中添加这样的东西:

    from matplotlib.ticker import FuncFormatter
    from quantiphy import Quantity
    
    time_fmtr = FuncFormatter(lambda v, p: Quantity(v, 's').render(prec=2))
    ax.xaxis.set_major_formatter(time_fmtr)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-27
      • 1970-01-01
      • 1970-01-01
      • 2021-07-06
      • 2014-03-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多