5.直方图
histogram
import plotly.offline as of
import plotly.graph_objs as go
inport numpy as np
s1 = np.random.RandomState(1)
x = s1.randn(1000)
data = [
go.Histogram(
x = x,
histnorm = 'probability'
)
]
'''
histnorm ----> 如果我们设定histnorm = 'probability' 则纵坐标变为落入区间内的样本频率
默认状态下表示直方图纵坐标落入区间内的样本数目
'''
fig = go.Figure(data=data)
of.init_notebook_mode()
of.iplot(fig)
重叠垂直直方图
我们在说说重叠垂直直方图的绘制
需要在Layout中设置barmode属性,将其改为‘overlay’
如果我们不对其进行设置,会出现Plotly默认将两个直方图的柱状宽度强制变窄
以满足重叠部分的显示需求。
下面我们来看下,数据有Numpy随机生成
s1 = np.random.RandomState(1)
x0 = s1.randn(1000)
x1 = s1.chisquare(5, 1000)
trace1 = go.Histogram(
x = x0,
histnorm = 'probability', # 出现的频率
opacity = 0.75
)
trace2 = go.Histogram(
x = x1,
histnorm = 'probability',
opacity = 0.75
)
data = [trace1, trace2]
layout = go.Layout(
barmode = 'overlay'
)
'''
barmode ----> layout中的参数, barmode='overlay'时,两个图会重叠
barmode='stack'时,两个图会进行堆叠
'''
fig = go.Figure(data = data, layout = layout)
of.init_notebook_mode()
of.iplot(fig)
层叠直方图
绘制层叠直方图同样需要设置barmode属性,将其设置为‘stack’
下面我们看一下使用Numpy随机生成相同的正态分布数据图的叠加效果
s1.np.random.RandomState(1)
x0 = s1.randn(1000)
x1 = s1.randn(1000)
trace1 = go.Histogram(
x = x0
)
trace2 = go.Histogram(
x = x1
)
data = [trace1, trace2]
layout = go.Layout(
barmode = 'stack'
)
fig = go.Figure(data=data, layout=layout)
of.init_notebook_mode()
of.iplot(fig)