sou*_*alo 2 python histogram plotly plotly-python
我正在尝试使用 python 中的 Plotly 绘制累积直方图,但使其看起来像“步骤”,即没有颜色且仅显示顶线的条形图。像这样的东西:
基本上,我试图重现以下 matplotlib 代码的行为:
import matplotlib.pyplot as plt
plt.hist(x, cumulative=True, histtype='step')
Run Code Online (Sandbox Code Playgroud)
到目前为止,我能做的最好的事情是:
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])
Run Code Online (Sandbox Code Playgroud)
那么有什么技巧呢?
如果您愿意在绘制数据之前处理分箱和累积,则可以使用go.Scatter线的 shape 属性设置为 的对象'hvh'。
阴谋:
代码: 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')
Run Code Online (Sandbox Code Playgroud)
我希望这是你可以使用的东西!
如果没有,请随时告诉我。
一些细节:
数据样本是使用np.random.normal(). x是平均值 = 50、sigma = 5 和 500 个观测值的采样正态分布。x然后放入 50 个 bin,使用np.histogram()它返回两个数组。这些用作绘图的数据源。
可能的替代方法:
我还尝试将您的代码片段与一些随机样本数据一起使用并包含shape='hvh'在您的line=dict(color="red", width=1). 但这似乎不起作用。我还考虑过修改您的布局go.Histogram(),以便仅绘制条形的顶线,但我认为这是不可能的。
| 归档时间: |
|
| 查看次数: |
8510 次 |
| 最近记录: |