Plotly:如何绘制累积的“步骤";直方图?
问题描述
我试图在 python 中使用 Plotly 绘制累积直方图,但让它看起来像步骤",即没有颜色的条形图,只显示顶线.像这样的:
I am trying to plot a cumulative histogram using Plotly in python, but make it look like "steps", i.e. bars with no color and only the top line is displayed. Something like this:
基本上,我正在尝试重现以下 matplotlib 代码的行为:
Basically, I'm trying to reproduce the behavior of the following matplotlib code:
import matplotlib.pyplot as plt
plt.hist(x, cumulative=True, histtype='step')
到目前为止,我能做的最好的事情是:
So far, the best I've been able to do is:
import plotly.graph_objs as go
from plotly.offline import iplot
h = go.Histogram(x=x,
cumulative=dict(enabled=True),
marker=dict(color="rgba(0,0,0,0)",
line=dict(color="red", width=1)))
iplot([h])
结果如下:
那么有什么诀窍呢?
解决方案
如果您愿意在绘制数据之前处理分箱和累积,您可以使用 go.线的 shape 属性设置为
对象.'hvh'
的散布
If you're willing to handle the binning and accumulation before you plot the data, you can use a go.Scatter
object with the shape property of the line set to 'hvh'
.
剧情:
代码: Jupyter Notebook 的设置
Code: Setup for a Jupyter Notebook
#imports
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import numpy as np
import pandas as pd
# qtconsole for debugging
#%qtconsole -- style vim
# Notebook settings
init_notebook_mode(connected=True)
# Some sample data
x = np.random.normal(50, 5, 500)
binned = np.histogram(x, bins=25, density=True)
plot_y = np.cumsum(binned[0])
# Line
trace1 = go.Scatter(
x=binned[1],
y=plot_y,
mode='lines',
name="X",
hoverinfo='all',
line=dict(color = 'rgb(1255, 0, 0)', shape='hvh'
)
)
data = [trace1]
# Layout
layout = dict(title = 'Binned data from normal distribution',
legend=dict(
y=0.5,
traceorder='reversed',
font=dict(
size=16
)
)
)
# Make figure
fig = dict(data=data, layout=layout)
# Plot
iplot(fig, filename='line-shapes')
我希望这是你可以使用的东西!
I hope this is something you can use!
如果没有,请随时告诉我.
Don't hesitate to let me know if not.
一些细节:
数据样本是使用 np.random.normal()
制作的.x
是平均值 = 50、sigma = 5 和 500 个观测值的采样正态分布.然后使用返回两个数组的 np.histogram()
将 x
放入 50 个 bin 中.这些用作绘图的数据源.
The data sample is made using np.random.normal()
. x
is a sampled normal distribution with mean = 50, sigma = 5 and 500 observations. x
is then put in 50 bins using np.histogram()
which returns two arrays. These are used as data source for the plot.
可能的替代方法:
我还尝试将您的代码段与一些随机样本数据一起使用,并在您的 line=dict(color="red", width=1)
shape='hvh'>.但这似乎不起作用.我还考虑过修改 go.Histogram()
的布局,以便只绘制条形的顶线,但我认为这是不可能的.
I also tried using your snippet with some random sample data and include shape='hvh'
in your line=dict(color="red", width=1)
. That did not seem to work though. I also considered modifying the layout of your go.Histogram()
so that only the top line of the bars were plotted, but I don't think it's possible.
相关文章