Python Matplotlib:绘制带有重叠边界删除的直方图

4
我正在使用Python中的Matplotlib绘制直方图,使用matplotlib.bar()函数。这给了我这样的图像:

enter image description here

我想要生成一个直方图,只绘制每个条形图的顶部和不直接与另一个条形图边框共享空间的侧面,就像这样:(我用gimp编辑过)

enter image description here

如何使用Python实现这一点?使用matplotlib的答案更可取,因为这是我最有经验的,但我也愿意尝试其他使用Python的方法。
值得一提的是,这里是相关代码:
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")

2
看一下 stepfilled 类型的直方图,并将面颜色设置为白色 -- http://matplotlib.org/examples/statistics/histogram_demo_histtypes.html - cphlewis
更多的版本:http://matplotlib.org/examples/api/filled_step.html - cphlewis
我的数据已经分组了,而且我无法访问原始的未分组数据,所以我不认为我可以使用 pyplot.hist - NeutronStar
1个回答

4

我想最简单的方法是使用步进函数而不是条形图:

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),step实际上无法正确绘制最后(第一)个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()

1
链接会过期,只有链接的答案长期来看会变得无用。请考虑在答案中添加详细描述和相关部分。 - Paul H

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接