如何在直方图中将标签居中 [英] How to center labels in histogram plot

查看:168
本文介绍了如何在直方图中将标签居中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似

[ 0.  2.  0.  0.  0.  0.  3.  0.  0.  0.  0.  0.  0.  0.  0.  2.  0.  0.
  0.  0.  0.  1.  0.  0.  0.  0.  0.  0.  0.  1.  0.  0.  0.  0.  0.  0.
  0.  1.  1.  0.  0.  0.  0.  2.  0.  3.  1.  0.  0.  2.  2.  0.  0.  0.
  0.  0.  0.  0.  0.  1.  1.  0.  0.  0.  0.  0.  0.  2.  0.  0.  0.  0.
  0.  1.  0.  0.  0.  0.  0.  0.  0.  0.  0.  3.  1.  0.  0.  0.  0.  0.
  0.  0.  0.  1.  0.  0.  0.  1.  2.  2.]

我想绘制一个直方图.我尝试过

I would like to plot a histogram of it. I have tried

import matplotlib.pyplot as plt
plt.hist(results, bins=range(5))
plt.show()

这给了我一个x轴标记为0.0 0.5 1.0 1.5 2.0 2.5 3.0. 3.5 4.0的直方图.

This gives me a histogram with the x-axis labelled 0.0 0.5 1.0 1.5 2.0 2.5 3.0. 3.5 4.0.

我希望x轴标记为0 1 2 3,而不是在每个条形的中心标记.你该怎么做?

I would like the x-axis to be labelled 0 1 2 3 instead with the labels in the center of each bar. How can you do that?

推荐答案

以下替代解决方案与plt.hist()兼容(例如,它的优点是您可以在pandas.DataFrame.hist()之后调用它.

The following alternative solution is compatible with plt.hist() (and this has the advantage for instance that you can call it after a pandas.DataFrame.hist().

import numpy as np

def bins_labels(bins, **kwargs):
    bin_w = (max(bins) - min(bins)) / (len(bins) - 1)
    plt.xticks(np.arange(min(bins)+bin_w/2, max(bins), bin_w), bins, **kwargs)
    plt.xlim(bins[0], bins[-1])

(OP并不严格要求最后一行,但是它会使输出更好)

(The last line is not strictly requested by the OP but it makes the output nicer)

这可以用在:

import matplotlib.pyplot as plt
bins = range(5)
plt.hist(results, bins=bins)
bins_labels(bins, fontsize=20)
plt.show()

这篇关于如何在直方图中将标签居中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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