Matplotlib-为每个垃圾箱贴标签 [英] Matplotlib - label each bin

查看:76
本文介绍了Matplotlib-为每个垃圾箱贴标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Matplotlib创建直方图:

I'm currently using Matplotlib to create a histogram:

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轴标签更有意义.

I'd like to make the x-axis labels a bit more meaningful.

首先,此处的x轴刻度线似乎仅限于5个刻度线.不管我做什么,似乎都无法更改-即使添加更多xticklabel,它也只会使用前五个.我不确定Matplotlib是如何计算出来的,但是我认为它是根据范围/数据自动计算出来的?

Firstly, the x-axis ticks here seem to be limited to five ticks. No matter what I do, I can't seem to change this - even if I add more xticklabels, it only uses the first five. I'm not sure how Matplotlib calculates this, but I assume it's auto-calculated from the range/data?

是否可以通过某种方式提高x-tick标签的分辨率-甚至可以将每个小节/小节的分辨率提高到一个?

Is there some way I can increase the resolution of x-tick labels - even to the point of one for each bar/bin?

(理想情况下,我还希望以微秒/毫秒为单位重新设置秒的格式,但这又是一个问题).

(Ideally, I'd also like the seconds to be reformatted in micro-seconds/milli-seconds, but that's a question for another day).

第二,我想要每个标有标签的栏-该垃圾箱中的实际数量以及所有垃圾箱总数的百分比.

Secondly, I'd like each individual bar labeled - with the actual number in that bin, as well as the percentage of the total of all bins.

最终输出可能看起来像这样:

The final output might look something like this:

Matplotlib是否有可能做到这一点?

Is something like that possible with Matplotlib?

干杯, 维克多

推荐答案

当然!要设置刻度线,恰好...设置刻度线(请参见matplotlib.pyplot.xticksax.set_xticks). (此外,您无需手动设置补丁的面色.您只需传递关键字参数即可.)

Sure! To set the ticks, just, well... Set the ticks (see matplotlib.pyplot.xticks or ax.set_xticks). (Also, you don't need to manually set the facecolor of the patches. You can just pass in a keyword argument.)

对于其余的部分,您将需要对标签做一些花哨的事情,但是matplotlib使其相当容易.

For the rest, you'll need to do some slightly more fancy things with the labeling, but matplotlib makes it fairly easy.

例如:

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()

这篇关于Matplotlib-为每个垃圾箱贴标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆