python - 在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()
解决方案
问题是你没有改变row
和col
你的子图。鉴于您没有提供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()
推荐阅读
- java - NoSuchBeanDefinitionException:没有名为“entityManagerFactory”的bean可用
- html - 为什么这个 Bootstrap 行覆盖的宽度大于屏幕宽度?
- angular - 离子形式验证最大长度不起作用
- c# - 一旦一个或多个文件在文件夹中包含无效字符,C#就会抛出异常错误
- android - java.lang.IllegalStateException: Activity 已被销毁(替换片段时)
- java - 时间和日期选择器的时间(以毫秒为单位)
- html - ng-repeat 从后端的 json 数组中获取值
- android - 尝试在空对象引用上调用虚拟方法“java.lang.String com.android.server.fingerprint.ClientMonitor.getOwnerString()”
- java - 启动 ActiveMQ 时打印的类路径错误中未检测到 Spring WebApplicationInitializer 类型
- android - 密封类中的 Kotlin 数据类