绘制多个饼图,其位置位于 for 循环中

Bou*_*uji 2 python pandas plotly

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

\n

我想使用 foor 循环迭代我的数据,为子图中的每个位置制作不同的饼图。\n我面临 2 个问题,我不知道如何在迭代时给出位置。\n而且我也不'即使我调用“show”方法,我的身材上也没有任何东西。

\n
import plotly.graph_objs as go\nfrom plotly.subplots import make_subplots\nlabels = stock_by_portals_private.index\n\nspec=[[{'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}, \n{'type':'domain'}, {'type':'domain'}],\n  [{'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}, {'type':'domain'}, \n{'type':'domain'}, {'type':'domain'}]]\n\nfig = make_subplots(rows=2, cols=7, specs=spec, print_grid=True)\ni = 1\nj = 1\nfor label in labels:\n    private = stock_by_portals_private[stock_by_portals_private.index == label]['id']\n    pro = stock_by_portals_pro[stock_by_portals_pro.index == label]['id']\n    fig.add_trace(go.Pie(labels=['PRO', 'PRIVATE'], values=[pro , private ],\\\n                     name="R\xc3\xa9partition des annonceurs par portail: " + str(label)), 1,1)\n\nfig.update_traces(hoverinfo='label+percent+name', textinfo='none')\nfig = go.Figure(fig)\nfig.show()\n
Run Code Online (Sandbox Code Playgroud)\n

rpa*_*nai 6

问题是你没有改变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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述