Matplotlib Xticklabels无法正常工作

时间:2011-06-14 09:42:47

标签: python matplotlib histogram graphing

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缺少标题(“垃圾邮件和火腿”)。 x和y轴标签都存在(虽然我没有为下面的示例打开它们。)
  2. x-tick-lables似乎完全被打破 - 而不是沿着所有条形下方的底部显示,它被渲染为图形左下方下方的一行数字,被切断。它似乎也禁用了我的Y轴标签。
  3. Histogram with broken xticklabels

    2。单位和SI前缀

    注意:不是特定的Matplotlib。

    直方图沿x轴有时间测量。这些范围从微秒范围到毫秒和第二范围。目前,图表以标准表示法将x轴标签渲染为秒。

    Time in seconds along x-axis

    我想友好格式我宁愿以毫秒/微秒值给出时间,单位显示。所以这意味着我想要一些友好的时间值格式,并且能够了解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/
    4. 但是,根据我的阅读,它似乎不像上面的任何处理SI前缀,或做这种友好的格式。有什么建议/备选方案吗?

2 个答案:

答案 0 :(得分:3)

1.1:PNG中缺少标题(“垃圾邮件和火腿”)。

你写了

pyplot.title='Foobar'

你想要

pyplot.title("Spam and Ham")

pyplot.title ='Foobar'只是用字符串替换title函数。

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是一个包含箱子中的计数的数组,而不是箱子位置;它是y轴,而不是x。而且,它已经是一个列表,所以无论如何都不应该使用[n]。我不确定你想做什么,但你可以从垃圾箱中制作字符串标签(除非你想要很多数字!)或者,如果你只想让xtick标签垂直,你可以使用

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

我担心我对单元库一无所知。

答案 1 :(得分:0)

要将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)