简体   繁体   English

从 matplotlib 中的直方图数据绘制折线图

[英]Plot line graph from histogram data in matplotlib

I have a numpy array of ints representing time periods, which I'm currently plotting in a histogram to get a nice distribution graph, using the following code:我有一个表示时间段的 numpy 整数数组,我目前正在使用以下代码将其绘制在直方图中以获得不错的分布图:

ax.hist(data,bins=100,range=(minimum,maximum),facecolor="r")

However I'm trying to modify this graph to represent the exact same data using a line instead of bars, so I can overlay more samples to the same plot and have them be clear (otherwise the bars overlap each other).但是,我正在尝试修改此图以使用线而不是条来表示完全相同的数据,因此我可以将更多样本叠加到同一个图中并使它们清晰(否则条相互重叠)。 What I've tried so far is to collate the data array into an array of tuples containing (time, count), and then plot it using到目前为止我所尝试的是将数据数组整理成包含(时间,计数)的元组数组,然后使用

ax.plot(data[:,0],data[:,1],color="red",lw=2)

However that's not giving me anything close, as I can't accurately simulate the bins option of the histogram in my plot.然而,这并没有给我任何接近的结果,因为我无法在我的情节中准确地模拟直方图的 bins 选项。 Is there a better way to do this?有一个更好的方法吗?

I am very late to the party - but maybe this will be useful to someone else.我参加聚会很晚 - 但也许这对其他人有用。 I think what you need to do is set the histtype parameter to 'step', ie我认为您需要做的是将 histt​​ype 参数设置为 'step',即

ax.hist(data,bins=100,range=(minimum,maximum),facecolor="r", histtype = 'step')

See also http://matplotlib.sourceforge.net/examples/pylab_examples/histogram_demo_extended.html另见http://matplotlib.sourceforge.net/examples/pylab_examples/histogram_demo_extended.html

You can save the output of hist and then plot it.您可以保存hist的输出,然后绘制它。

import numpy as np
import pylab as p

data=np.array(np.random.rand(1000))
y,binEdges=np.histogram(data,bins=100)
bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
p.plot(bincenters,y,'-')
p.show()

Seaborn had what I needed: Seaborn 有我需要的东西:

import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt

sb.distplot(data, hist=False)
plt.show()

如果使用 seaborn 库,因为 distplot 函数已被弃用:

import seaborn

seaborn.histplot(data, element = 'poly', fill= False)

试试ax.plot(zip(*data)[:][0],zip(*data)[:][1],color="red",lw=2)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM