首页 > 解决方案 > 在for循环中绘制多个带有位置的饼图

问题描述

我正在尝试用 Plotly 制作一个 2*7 的子图。

我想使用一个 foo 循环来迭代我的数据,以便为子图中的每个位置制作不同的饼图。我面临 2 个问题,我不知道如何在迭代时给出位置。即使我调用“显示”方法,我的身材也没有任何东西。

import plotly.graph_objs as go
from plotly.subplots import make_subplots
labels = stock_by_portals_private.index

spec=[[{'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}, 
{'type':'domain'}, {'type':'domain'}],
  [{'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}, 
{'type':'domain'}, {'type':'domain'}]]

fig = make_subplots(rows=2, cols=7, specs=spec, print_grid=True)
i = 1
j = 1
for label in labels:
    private = stock_by_portals_private[stock_by_portals_private.index == label]['id']
    pro = stock_by_portals_pro[stock_by_portals_pro.index == label]['id']
    fig.add_trace(go.Pie(labels=['PRO', 'PRIVATE'], values=[pro , private ],\
                     name="Répartition des annonceurs par portail: " + str(label)), 1,1)

fig.update_traces(hoverinfo='label+percent+name', textinfo='none')
fig = go.Figure(fig)
fig.show()

标签: pythonpandasplotly

解决方案


问题是你没有改变rowcol你的子图。鉴于您没有提供mcve,我制作了一个示例。

import plotly.graph_objs as go
from plotly.subplots import make_subplots

# data for this example
import plotly.express as px
df = px.data.gapminder().query("year == 2007")

# We want a subplot for every continent
lst = list(df.groupby('continent'))

# here we want our grid to be 2 x 3
rows = 2
cols = 3
# continents are the first element in l
subplot_titles = [l[0] for l in lst]

# a compact and general version of what you did
specs = [[{'type':'domain'}] * cols] * rows

# here the only difference from your code
# are the titles for subplots
fig = make_subplots(
        rows=rows,
        cols=cols,
        subplot_titles=subplot_titles,
        specs=specs,
        print_grid=True)

for i, l in enumerate(lst):
    # basic math to get col and row
    row = i // cols + 1
    col = i % (rows + 1) + 1
    # this is the dataframe for every continent
    d = l[1]
    fig.add_trace(
        go.Pie(labels=d["country"],
               values=d["pop"],
               showlegend=False,
               textposition='inside',
               textinfo='label+percent'),
         row=row,
         col=col
    
    )
    
fig.update_layout(title="Population by Continent", title_x=0.5)
fig.show()

在此处输入图像描述


推荐阅读