Matplotlib Xticklabels not working
1. X-ticklabel不起作用
我正在使用Matplotlib从一些测量结果生成直方图:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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看起来不错,除了两个问题:
2.单位和SI前缀
注意:不是Matplotlib特有的。
直方图沿x轴具有时间测量值。这些范围从微秒范围到毫秒和秒范围。此刻,该图形将x轴标签呈现为标准表示法中的秒数。
我想友好地格式化,我希望时间以毫秒/微秒的值给出,并显示单位。因此,这意味着我想通过SI前缀来友好地格式化时间值。
实际上,它可能与此处的示例程序非常相似:
http://diveintopython3.org/your-first-python-program.html
我确实注意到有一些Python库可以处理单位:
但是,从我阅读的内容来看,似乎没有上述任何句柄SI前缀,也没有进行这种友好的格式化。有什么建议/替代品吗?
1.1:PNG中缺少标题("垃圾邮件和火腿")。
你写了
1 | pyplot.title='Foobar' |
你要
1 | pyplot.title("Spam and Ham") |
pyplot.title ='Foobar'只是将标题函数替换为字符串。
1.2:x刻度线似乎完全损坏
ISTM
1 2 3 4 5 6 | >>> 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 |
n是一个数组,在箱中包含计数,而不是箱位置;它是y轴,而不是x。而且,它已经是一个列表,因此无论如何都不需要使用[n]。我不确定您要做什么,但是您可以从垃圾箱中创建字符串标签(除非您想要很多数字!),或者,如果您只希望xtick标签是垂直的,则可以使用
1 2 | for label in ax.get_xticklabels(): label.set_rotation('vertical') |
恐怕我对单元库一无所知。
要将SI前缀添加到轴标签,您需要使用QuantiPhy。实际上,在其文档中有一个示例显示了如何执行此操作:MatPlotLib示例。
我认为您可以在代码中添加如下内容:
1 2 3 4 5 | 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) |