Python 如何使用自定义大小在Plotly中绘制饼图子图
Plotly是一个开源的、交互式的、基于浏览器的Python图表库。Python用户可以使用Plotly生成不同类型的图表,包括科学图表、3D图形、统计图表、金融图表等。
在本教程中,我们将展示如何使用Plotly将饼图作为子图以及自定义大小。
- 在这里,我们将使用 plotly.offline 模块生成离线图。
-
我们将使用 plotly.graph_objects 模块生成图形。它包含了很多生成图表的方法。
-
为了创建子图,我们将使用make_subplots()方法。
按照以下步骤绘制饼图子图。
第1步
导入 plotly.offline 模块以生成离线图。
from plotly.offline import plot
第2步
导入 plotly.graph_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() 方法来为Pie图设置下列值的traces –
# 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)
同样,您可以尝试将不同类型的图表创建为图片。
输出
它将在浏览器上显示以下输出: