Matplotlib – 标记每个bin
我目前正在使用Matplotlib创build一个直方图:
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('Spam and Ham') pyplot.xlabel('Time (in seconds)') pyplot.ylabel('Bits of Ham') pyplot.savefig(output_filename)
我想让x轴标签更有意义。
首先,这里的x轴刻度似乎限于五个刻度。 不pipe我做什么,似乎都无法改变这一点 – 即使我添加了更多的xticklabels,它也只使用前五个。 我不确定Matplotlib如何计算这个值,但是我认为它是从范围/数据自动计算的?
有什么办法可以提高x-tick标签的分辨率 – 甚至是每个bar / bin一个点的分辨率 ?
(理想情况下,我也希望秒数以毫秒/毫秒为单位进行重新格式化,但这是另一天的问题)。
其次,我希望每个单独的酒吧都标有这个垃圾箱的实际数量,以及所有垃圾箱的总数的百分比。
最终的输出可能看起来像这样:
是Matplotlib可能吗?
干杯,维克多
当然! 设置刻度,只是,好…设置刻度(请参阅matplotlib.pyplot.xticks
或ax.set_xticks
)。 (另外,您不需要手动设置补丁的facecolor,只需要传入一个关键字参数。)
其余的,你需要做一些稍微更漂亮的标签,但matplotlib使它相当容易。
举个例子:
import matplotlib.pyplot as plt import numpy as np from matplotlib.ticker import FormatStrFormatter data = np.random.randn(82) fig, ax = plt.subplots() counts, bins, patches = ax.hist(data, facecolor='yellow', edgecolor='gray') # Set the ticks to be at the edges of the bins. ax.set_xticks(bins) # Set the xaxis's tick labels to be formatted with 1 decimal place... ax.xaxis.set_major_formatter(FormatStrFormatter('%0.1f')) # Change the colors of bars at the edges... twentyfifth, seventyfifth = np.percentile(data, [25, 75]) for patch, rightside, leftside in zip(patches, bins[1:], bins[:-1]): if rightside < twentyfifth: patch.set_facecolor('green') elif leftside > seventyfifth: patch.set_facecolor('red') # Label the raw counts and the percentages below the x-axis... bin_centers = 0.5 * np.diff(bins) + bins[:-1] for count, x in zip(counts, bin_centers): # Label the raw counts ax.annotate(str(count), xy=(x, 0), xycoords=('data', 'axes fraction'), xytext=(0, -18), textcoords='offset points', va='top', ha='center') # Label the percentages percent = '%0.0f%%' % (100 * float(count) / counts.sum()) ax.annotate(percent, xy=(x, 0), xycoords=('data', 'axes fraction'), xytext=(0, -32), textcoords='offset points', va='top', ha='center') # Give ourselves some more room at the bottom of the plot plt.subplots_adjust(bottom=0.15) plt.show()
要将SI前缀添加到要使用QuantiPhy的轴标签中。 事实上,在它的文档中有一个例子,展示了如何做到这一点: MatPlotLib示例 。
我想你会添加这样的代码:
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)