使用 Matplotlib 在对数刻度上绘制直方图 [英] plotting a histogram on a Log scale with Matplotlib

查看:55
本文介绍了使用 Matplotlib 在对数刻度上绘制直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Pandas DataFrame,它在一个系列中具有以下值

I have a pandas DataFrame that has the following values in a Series

x = [2, 1, 76, 140, 286, 267, 60, 271, 5, 13, 9, 76, 77, 6, 2, 27, 22, 1, 12, 7, 19, 81, 11, 173, 13, 7, 16, 19, 23, 197, 167, 1]

我被指示使用 Python 3.6 在 Jupyter notebook 中绘制两个直方图.不会出汗吧?

I was instructed to plot two histograms in a Jupyter notebook with Python 3.6. No sweat right?

x.plot.hist(bins=8)
plt.show()

我选择了 8 个垃圾箱,因为这对我来说看起来最好.我还被指示用 x 的对数绘制另一个直方图.

I chose 8 bins because that looked best to me. I have also been instructed to plot another histogram with the log of x.

x.plot.hist(bins=8)
plt.xscale('log')
plt.show()

这个直方图看起来很糟糕.我做的不对吗?我试过摆弄情节,但我试过的一切似乎都让直方图看起来更糟.示例:

This histogram looks TERRIBLE. Am I not doing something right? I've tried fiddling around with the plot, but everything I've tried just seems to make the histogram look even worse. Example:

x.plot(kind='hist', logx=True)

除了将 X 的对数绘制为直方图之外,我没有得到任何指示.

I was not given any instructions other than plot the log of X as a histogram.

我真的很感激任何帮助!!!

I really appreciate any help!!!

作为记录,我已经导入了 pandas、numpy 和 matplotlib,并指定该图应该是内联的.

For the record, I have imported pandas, numpy, and matplotlib and specified that the plot should be inline.

推荐答案

hist 调用中指定 bins=8 意味着最小值和最大值之间的范围是平均分成 8 个垃圾箱.在线性尺度上相等的东西在对数尺度上是扭曲的.

Specifying bins=8 in the hist call means that the range between the minimum and maximum value is divided equally into 8 bins. What is equal on a linear scale is distorted on a log scale.

您可以做的是指定直方图的 bin,使它们的宽度不相等,使它们在对数刻度上看起来相等.

What you could do is specify the bins of the histogram such that they are unequal in width in a way that would make them look equal on a logarithmic scale.

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

x = [2, 1, 76, 140, 286, 267, 60, 271, 5, 13, 9, 76, 77, 6, 2, 27, 22, 1, 12, 7, 
     19, 81, 11, 173, 13, 7, 16, 19, 23, 197, 167, 1]
x = pd.Series(x)

# histogram on linear scale
plt.subplot(211)
hist, bins, _ = plt.hist(x, bins=8)

# histogram on log scale. 
# Use non-equal bin sizes, such that they look equal on log scale.
logbins = np.logspace(np.log10(bins[0]),np.log10(bins[-1]),len(bins))
plt.subplot(212)
plt.hist(x, bins=logbins)
plt.xscale('log')
plt.show()

这篇关于使用 Matplotlib 在对数刻度上绘制直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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