【问题标题】:Python Matplotlib: plotting histogram with overlapping boundaries removedPython Matplotlib:绘制删除重叠边界的直方图
【发布时间】:2016-06-23 17:19:55
【问题描述】:

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

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

如何使用 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")

【问题讨论】:

标签: python matplotlib histogram


【解决方案1】:

我想最简单的方法是使用 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()

【讨论】:

  • 随着时间的推移,链接腐烂和仅链接的答案变得无用。请考虑在答案中添加细节和相关部分。