【问题标题】:How to plot a scatter plot using the histogram output in matplotlib?如何使用 matplotlib 中的直方图输出绘制散点图?
【发布时间】:2013-08-21 22:51:48
【问题描述】:

我想绘制一个类似于这个的散点图:

我可以根据我的数据绘制直方图,但我想要相同数据的散点图。有什么方法可以使用 hist() 方法输出作为散点图的输入?还是有其他方法可以使用 matplotlib 中的 hist() 方法绘制散点图? 用于绘制直方图的代码如下:

data = get_data()
plt.figure(figsize=(7,4))
ax = plt.subplots()
plt.hist(data,histtype='bar',bins = 100,log=True)
plt.show()

【问题讨论】:

  • 看看at this answer,有一个代码可以绘制2D或3D直方图...

标签: python matplotlib scatter-plot


【解决方案1】:

我认为您正在寻找以下内容:

基本上plt.hist() 输出两个数组(正如 Nordev 指出的一些补丁)。第一个是每个 bin (n) 中的计数,第二个是 bin 的边缘。

import matplotlib.pylab as plt
import numpy as np

# Create some example data
y = np.random.normal(5, size=1000)

# Usual histogram plot
fig = plt.figure()
ax1 = fig.add_subplot(121)
n, bins, patches = ax1.hist(y, bins=50)  # output is two arrays

# Scatter plot
# Now we find the center of each bin from the bin edges
bins_mean = [0.5 * (bins[i] + bins[i+1]) for i in range(len(n))]
ax2 = fig.add_subplot(122)
ax2.scatter(bins_mean, n)

如果没有更多的问题描述,这是我能想到的最好的方法。对不起,如果我误解了。

【讨论】:

  • output 不仅包含两个数组,还包含Patch 对象的列表。为什么不使用“标准”n, bins, patches = ax1.hist(...,因为这会将返回的数组/列表解包到相应的变量中? IMO 这些是更直观的变量名称,使代码更容易阅读。
  • 如果您不想要补丁,只需使用np.histogramplt.hist 只是 histogram 的一个包装器,它使用 plt.bar 绘制结果。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-14
  • 2018-06-23
  • 2013-08-29
  • 2016-05-11
  • 1970-01-01
  • 2016-06-09
相关资源
最近更新 更多