如何使用matplotlib中的直方图输出绘制散点图?

2024-06-16 09:43:37 发布

您现在位置:Python中文网/ 问答频道 /正文

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

enter image description here

我可以根据我的数据绘制柱状图,但我想要相同数据的散点图。有什么方法可以使用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()

Tags: 数据方法代码datagetmatplotlib绘制plt
1条回答
网友
1楼 · 发布于 2024-06-16 09:43:37

我想你要找的是:

本质上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)

Example

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

相关问题 更多 >