直方图 Matplotlib

发布于 2024-10-22 01:06:27 字数 144 浏览 1 评论 0原文

所以我有一个小问题。我在 scipy 中有一个数据集,它已经是直方图格式,所以我有箱的中心和每个箱的事件数。我现在如何绘制直方图。我试着这么做

bins, n=hist()

,但它不喜欢那样。有什么建议吗?

So I have a little problem. I have a data set in scipy that is already in the histogram format, so I have the center of the bins and the number of events per bin. How can I now plot is as a histogram. I tried just doing

bins, n=hist()

but it didn't like that. Any recommendations?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

七禾 2024-10-29 01:06:27
import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
hist, bins = np.histogram(x, bins=50)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.show()

在此处输入图像描述

面向对象的界面也很简单:

fig, ax = plt.subplots()
ax.bar(center, hist, align='center', width=width)
fig.savefig("1.png")

如果您使用自定义(非常量)垃圾箱,则您可以可以使用np.diff计算宽度,将宽度传递给ax.bar并使用ax.set_xticks来标记bin边缘:

import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
bins = [0, 40, 60, 75, 90, 110, 125, 140, 160, 200]
hist, bins = np.histogram(x, bins=bins)
width = np.diff(bins)
center = (bins[:-1] + bins[1:]) / 2

fig, ax = plt.subplots(figsize=(8,3))
ax.bar(center, hist, align='center', width=width)
ax.set_xticks(bins)
fig.savefig("/tmp/out.png")

plt.show()

< a href="https://i.sstatic.net/tdVmV.png">在此处输入图像描述

import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
hist, bins = np.histogram(x, bins=50)
width = 0.7 * (bins[1] - bins[0])
center = (bins[:-1] + bins[1:]) / 2
plt.bar(center, hist, align='center', width=width)
plt.show()

enter image description here

The object-oriented interface is also straightforward:

fig, ax = plt.subplots()
ax.bar(center, hist, align='center', width=width)
fig.savefig("1.png")

If you are using custom (non-constant) bins, you can pass compute the widths using np.diff, pass the widths to ax.bar and use ax.set_xticks to label the bin edges:

import matplotlib.pyplot as plt
import numpy as np

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
bins = [0, 40, 60, 75, 90, 110, 125, 140, 160, 200]
hist, bins = np.histogram(x, bins=bins)
width = np.diff(bins)
center = (bins[:-1] + bins[1:]) / 2

fig, ax = plt.subplots(figsize=(8,3))
ax.bar(center, hist, align='center', width=width)
ax.set_xticks(bins)
fig.savefig("/tmp/out.png")

plt.show()

enter image description here

醉南桥 2024-10-29 01:06:27

如果您不想要条形图,可以像这样绘制它:

import numpy as np
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

bins, edges = np.histogram(x, 50, normed=1)
left,right = edges[:-1],edges[1:]
X = np.array([left,right]).T.flatten()
Y = np.array([bins,bins]).T.flatten()

plt.plot(X,Y)
plt.show()

直方图

If you don't want bars you can plot it like this:

import numpy as np
import matplotlib.pyplot as plt

mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

bins, edges = np.histogram(x, 50, normed=1)
left,right = edges[:-1],edges[1:]
X = np.array([left,right]).T.flatten()
Y = np.array([bins,bins]).T.flatten()

plt.plot(X,Y)
plt.show()

histogram

嘦怹 2024-10-29 01:06:27

我知道这并不能回答你的问题,但当我搜索直方图的 matplotlib 解决方案时,我总是会出现在这个页面上,因为简单的 histogram_demo 已从 matplotlib 示例库页面中删除。

这是一个不需要导入 numpy 的解决方案。我只导入 numpy 来生成要绘制的数据 x 。它依赖于函数 hist 而不是函数 bar@unutbu 回答

import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

import matplotlib.pyplot as plt
plt.hist(x, bins=50)
plt.savefig('hist.png')

输入图像描述这里

另请查看 matplotlib gallerymatplotlib 示例

I know this does not answer your question, but I always end up on this page, when I search for the matplotlib solution to histograms, because the simple histogram_demo was removed from the matplotlib example gallery page.

Here is a solution, which doesn't require numpy to be imported. I only import numpy to generate the data x to be plotted. It relies on the function hist instead of the function bar as in the answer by @unutbu.

import numpy as np
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)

import matplotlib.pyplot as plt
plt.hist(x, bins=50)
plt.savefig('hist.png')

enter image description here

Also check out the matplotlib gallery and the matplotlib examples.

晨曦÷微暖 2024-10-29 01:06:27

我刚刚意识到 hist 文档明确说明了当您已经有了 np.histogram 时要做什么。

counts, bins = np.histogram(data)
plt.hist(bins[:-1], bins, weights=counts)

这里重要的部分是您的计数只是权重。如果你这样做了,你就不再需要 bar 函数了

I just realized that the hist documentation is explicit about what to do when you already have an np.histogram

counts, bins = np.histogram(data)
plt.hist(bins[:-1], bins, weights=counts)

The important part here is that your counts are simply the weights. If you do it like that, you don't need the bar function anymore

郁金香雨 2024-10-29 01:06:27

从 matplotlib 3.4.0 开始,

新的 plt.stairs (或< strong>ax.stairs) 直接与 np.histogram 配合使用:

  • np.histogram 返回计数和边缘
  • < a href="https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.stairs.html" rel="noreferrer">plt.stairs< /a> 接受计数和边缘

例如,给定 unutbu 的示例 x = 100 + 15 * np.random.randn(10000)

counts, edges = np.histogram(x, bins=50)
plt.stairs(counts, edges, fill=True)


plt.stairs with np.histogram

或者,直接将 np.histogram 解压到plt.stairs

plt.stairs(*np.histogram(x, bins=50), fill=True)

请参阅官方 matplotlib 库,了解 如何使用楼梯图

As of matplotlib 3.4.0

The new plt.stairs (or ax.stairs) works directly with np.histogram:

  • np.histogram returns counts and edges
  • plt.stairs accepts counts and edges

For example, given unutbu's sample x = 100 + 15 * np.random.randn(10000):

counts, edges = np.histogram(x, bins=50)
plt.stairs(counts, edges, fill=True)


plt.stairs with np.histogram

Alternatively, unpack np.histogram directly into plt.stairs:

plt.stairs(*np.histogram(x, bins=50), fill=True)

See the official matplotlib gallery for more example of how to use stair plots.

昔梦 2024-10-29 01:06:27

如果您愿意使用 pandas

pandas.DataFrame({'x':hist[1][1:],'y':hist[0]}).plot(x='x',kind='bar')

If you're willing to use pandas:

pandas.DataFrame({'x':hist[1][1:],'y':hist[0]}).plot(x='x',kind='bar')
香草可樂 2024-10-29 01:06:27

这可能对某人有用。

Numpy 的直方图函数返回每个 bin 的边缘,而不是 bin 的值。这对于浮点数来说是有意义的,浮点数可以位于一个区间内,但在处理离散值或整数(0、1、2 等)时可能不是所需的结果。特别是,从 np.histogram 返回的 bin 长度不等于计数/密度的长度。

为了解决这个问题,我使用 np.digitize 来量化输入,并计算每个 bin 的计数分数。您可以轻松编辑以获得整数计数。

def compute_PMF(data):
    import numpy as np
    from collections import Counter
    _, bins = np.histogram(data, bins='auto', range=(data.min(), data.max()), density=False)
    h = Counter(np.digitize(data,bins) - 1)
    weights = np.asarray(list(h.values())) 
    weights = weights / weights.sum()
    values = np.asarray(list(h.keys()))
    return weights, values
####

参考文献:

[1] https://docs.scipy.org /doc/numpy/reference/ generated/numpy.histogram.html

[2]
https://docs.scipy.org/doc/numpy/参考/生成/numpy.digitize.html

This might be useful for someone.

Numpy's histogram function returns the edges of each bin, rather than the value of the bin. This makes sense for floating-point numbers, which can lie within an interval, but may not be the desired result when dealing with discrete values or integers (0, 1, 2, etc). In particular, the length of bins returned from np.histogram is not equal to the length of the counts / density.

To get around this, I used np.digitize to quantize the input, and count the fraction of counts for each bin. You could easily edit to get the integer number of counts.

def compute_PMF(data):
    import numpy as np
    from collections import Counter
    _, bins = np.histogram(data, bins='auto', range=(data.min(), data.max()), density=False)
    h = Counter(np.digitize(data,bins) - 1)
    weights = np.asarray(list(h.values())) 
    weights = weights / weights.sum()
    values = np.asarray(list(h.keys()))
    return weights, values
####

Refs:

[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html

[2]
https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文