gpt4 book ai didi

Python Matplotlib : plotting histogram with overlapping boundaries removed

转载 作者:太空狗 更新时间:2023-10-30 02:57:11 25 4
gpt4 key购买 nike

我正在使用 Python 中的 Matplotlib 和 matplotlib.bar() 函数绘制直方图。这给了我看起来像这样的情节:

enter image description here

我正在尝试生成一个直方图,该直方图仅绘制每个条形的上限以及不直接与另一个条形边界共享空间的边,更像这样:(我使用 gimp 编辑了它)

enter image description here

如何使用 Python 实现此目的?使用 matplotlib 的答案更可取,因为这是我最有经验的,但我对任何使用 Python 的作品持开放态度。

关于它的值(value),这里是相关代码:

import numpy as np
import matplotlib.pyplot as pp

bin_edges, bin_values = np.loadtxt("datafile.dat",unpack=True)
bin_edges = np.append(bin_edges,500.0)

bin_widths = []
for j in range(len(bin_values)):
bin_widths.append(bin_edges[j+1] - bin_edges[j])

pp.bar(bin_edges[:-1],bin_values,width=bin_widths,color="none",edgecolor='black',lw=2)


pp.savefig("name.pdf")

最佳答案

我想最简单的方法是使用 step 函数而不是 bar: http://matplotlib.org/examples/pylab_examples/step_demo.html

例子:

import numpy as np
import matplotlib.pyplot as pp

# Simulate data
bin_edges = np.arange(100)
bin_values = np.exp(-np.arange(100)/5.0)

# Prepare figure output
pp.figure(figsize=(7,7),edgecolor='k',facecolor='w')
pp.step(bin_edges,bin_values, where='post',color='k',lw=2)
pp.tight_layout(pad=0.25)
pp.show()

如果给定的 bin_edges 代表左边缘,请使用 where='post';如果他们在右边,使用 where='pre'。我看到的唯一问题是,如果您使用 post (pre),该步骤并没有真正正确地绘制最后一个(第一个)bin。但是您可以在数据之前/之后添加另一个 0 bin,以使其正确绘制所有内容。

示例 2 - 如果您想对一些数据进行分箱并绘制直方图,您可以这样做:

# Simulate data
data = np.random.rand(1000)

# Prepare histogram
nBins = 100
rng = [0,1]
n,bins = np.histogram(data,nBins,rng)
x = bins[:-1] + 0.5*np.diff(bins)

# Prepare figure output
pp.figure(figsize=(7,7),edgecolor='k',facecolor='w')
pp.step(x,n,where='mid',color='k',lw=2)
pp.show()

关于Python Matplotlib : plotting histogram with overlapping boundaries removed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37998017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com