0
点赞
收藏
分享

微信扫一扫

如何在Python Plotly中将饼图绘制为具有自定义大小的子图?


Plotly是一个开源的,交互式的,基于浏览器的Python图表库。Python用户可以使用Plotly生成不同类型的图表,包括科学图表,3D图形,统计图表,财务图表等。

在本教程中,我们将展示如何使用 Plotly 将饼图绘制为具有自定义大小的子图。

  • 在这里,我们将使用 plotly.offline 模块来生成一个离线绘图。
  • 我们将使用 plotly.graph_objects 模块生成数字。它包含很多生成图表的方法。
  • 要创建子图,我们将使用 make_subplots() 方法。

按照以下步骤将饼图绘制为子图。

步骤 1

导入plotly.offline模块以生成离线绘图。


from plotly.offline import plot

from plotly.offline import plot


步骤 2

plotly.graphs_objs模块和别名导入为 go

import plotly.graphs_objs as go

步骤 3

使用 make_subplots() 方法生成绘图类型为“饼图”的“行”和“列”。


fig = make_subplots(
rows=1, cols=2,
specs=[[
{"type": "pie"},
{"type": "pie"}
]]
)


步骤 4

使用 add_trace() 方法为饼图设置跟踪,这些值为 -

# Set traces for the first pie chart
fig.add_trace(go.Pie(
values=[16, 15, 12, 6, 5, 4, 42],
labels=["green", "red", "blue", "yellow", "orange", "purple"],
domain=dict(x=[0, 0.5]),
name="colors1"),
row=1, col=1
)

# Traces for the second pie chart
fig.add_trace(go.Pie(
values=[27, 11, 25, 8, 1, 3, 25],
labels=["white", "grey", "green", "maroon", "pink","red" ],

domain=dict(x=[0.5, 1.0]),
name="colors2"),
row=1, col=2
)


这是将饼图显示为具有自定义大小的子图的完整代码 -


from plotly.subplots import make_subplots import plotly.graph_objects as go from plotly.offline import plot # Create subplots fig = make_subplots( rows=1, cols=2, specs=[[{"type": "pie"}, {"type": "pie"}]] ) # Set traces for the pie chart fig.add_trace(go.Pie( values=[16, 15, 12, 6, 5, 4, 42], labels=["green", "red", "blue", "yellow", "orange", "purple" ], domain=dict(x=[0, 0.5]), name="colors1"), row=1, col=1 ) # Traces for the second pie chart fig.add_trace(go.Pie( values=[27, 11, 25, 8, 1, 3, 25], labels=["white", "grey", "green", "maroon", "pink","red" ], domain=dict(x=[0.5, 1.0]), name="colors2"), row=1, col=2 ) # Plot an image plot(fig)

同样,您可以尝试将不同类型的图形创建为图像。

输出

它将在浏览器上显示以下输出 -

如何在Python Plotly中将饼图绘制为具有自定义大小的子图?_子图

举报

相关推荐

0 条评论