如何在 Plotly 中创建分组箱线图?
Plotly 是一个Python库,用于设计图形,尤其是交互式图形。它可以绘制各种图形和图表,如直方图、条形图、箱线图、散布图等等。它主要用于数据分析和财务分析。 plotly 是一个交互式可视化库。
什么是分组箱线图?
分组箱线图是按组和子组进行分类的箱线图。 Origin 支持从索引数据或原始数据绘制分组箱形图。组合箱线图在展示上更易于理解和高效,并且在布局中占用的空间更少。
创建分组箱线图
它可以使用图形类的add_trace()方法创建。 add_trace() 方法允许我们在单个图中添加多个跟踪。让我们看看下面的例子
示例 1:箱线图的垂直分组
Python3
import plotly.graph_objects as go
fig = go.Figure()
# Defining x axis
x = ['a', 'a', 'a', 'b', 'b', 'b']
fig.add_trace(go.Box(
# defining y axis in corresponding
# to x-axis
y=[1, 2, 6, 4, 5, 6],
x=x,
name='A',
marker_color='green'
))
fig.add_trace(go.Box(
y=[2, 3, 4, 1, 2, 6],
x=x,
name='B',
marker_color='yellow'
))
fig.add_trace(go.Box(
y=[2, 5, 6, 7, 8, 1],
x=x,
name='C',
marker_color='blue'
))
fig.update_layout(
# group together boxes of the different
# traces for each value of x
boxmode='group'
)
fig.show()
Python3
import plotly.graph_objects as go
fig = go.Figure()
# Defining y axis
y = ['a', 'a', 'a', 'b', 'b', 'b']
fig.add_trace(go.Box(
# defining x axis in corresponding
# to y-axis
y=y,
x=[1, 2, 6, 4, 5, 6],
name='A',
marker_color='green'
))
fig.add_trace(go.Box(
y=y,
x=[2, 3, 4, 1, 2, 6],
name='B',
marker_color='yellow'
))
fig.add_trace(go.Box(
y=y,
x=[2, 5, 6, 7, 8, 1],
name='C',
marker_color='blue'
))
fig.update_layout(
# group together boxes of the different
# traces for each value of y
boxmode='group'
)
# changing the orientation to horizontal
fig.update_traces(orientation='h')
fig.show()
输出:
示例 2:箱线图的水平分组
Python3
import plotly.graph_objects as go
fig = go.Figure()
# Defining y axis
y = ['a', 'a', 'a', 'b', 'b', 'b']
fig.add_trace(go.Box(
# defining x axis in corresponding
# to y-axis
y=y,
x=[1, 2, 6, 4, 5, 6],
name='A',
marker_color='green'
))
fig.add_trace(go.Box(
y=y,
x=[2, 3, 4, 1, 2, 6],
name='B',
marker_color='yellow'
))
fig.add_trace(go.Box(
y=y,
x=[2, 5, 6, 7, 8, 1],
name='C',
marker_color='blue'
))
fig.update_layout(
# group together boxes of the different
# traces for each value of y
boxmode='group'
)
# changing the orientation to horizontal
fig.update_traces(orientation='h')
fig.show()
输出: