您最好的选择是使用像count, index = np.histogram(df['data'], bins=25) 这样的numpy 处理直方图,然后使用go.Scatter() 并将线型设置为horizontal, vertical, horizontal 和line=dict(width = 1, shape='hvh')。看看最后一节为什么go.Histogram() 不是您的最佳选择。加上go.Scatter() 的布局的其他一些规范,下面的 sn-p 将产生以下图:
完整代码
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import plotly.io as pio
import plotly.express as px
pio.templates.default = "plotly_white"
# random numbers to a df
np.random.seed(12)
df = pd.DataFrame({'data': np.random.randn(500)})
# produce histogram data wiht numpy
count, index = np.histogram(df['data'], bins=25)
# plotly, go.Scatter with line shape set to 'hvh'
fig = go.Figure()
fig.add_traces(go.Scatter(x=index, y = count,
line=dict(width = 1, shape='hvh')))
# y-axis cosmetics
fig.update_yaxes(
showgrid=False,
ticks="inside",
tickson="boundaries",
ticklen=10,
showline=True,
linewidth=1,
linecolor='black',
mirror=True,
zeroline=False)
# x-axis cosmetics
fig.update_xaxes(
showgrid=False,
ticks="inside",
tickson="boundaries",
ticklen=10,
showline=True,
linewidth=1,
linecolor='black',
mirror=True,
zeroline=False)
fig.show()
为什么是go.Scatter() 而不是go.Histogram()?
使用fig = go.Figure(data=[go.Histogram(x=x)]) 的方法最接近您想要的情节是这样的:
这非常接近,但您特别想排除每个“条”的垂直线。而且我还没有找到使用go.Histogram 设置排除或隐藏它们的方法。
go.Histogram() 的代码
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import plotly.io as pio
import plotly.express as px
pio.templates.default = "plotly_white"
import numpy as np
x = np.random.randn(500)
fig = go.Figure(data=[go.Histogram(x=x)])
fig.update_traces(marker=dict(color='rgba(0,0,0,0)', line=dict(width=1, color='blue')))
fig.show()