【发布时间】:2020-11-22 23:07:34
【问题描述】:
我知道,如果我想设置所有的子图标题,那么我可以在声明图形时这样做。
import pandas as pd
import plotly.graph_objs as go
from plotly.subplots import make_subplots
fig = make_subplots(
###
subplot_titles=['Plot 1', 'Plot 2', 'Plot 3', 'Plot 4', etc.]
)
但是,我在一个循环中创建每个子图,我认为在该过程中设置每个子图的标题是最简单的。就我而言,我根据日期创建了一个 groupby 对象,然后循环遍历每个组(日期)数据框。每个数据框都用于创建子图,我希望标题是日期。我知道我可以在循环之前解决这个问题并将 subplot_titles 设置为正常,但它似乎是循环中的单行。如果重要的话,我添加的痕迹是等值线。我不会包含工作数据集,因为我的代码工作正常——我只想知道我需要添加哪一行代码。
#Create groupby object, splitting data frame into separate data frames based on 'State'
death_counts_gbo = death_counts_by_week.groupby('End Week')
#Prepare subplots for choropleths
rows = 4
cols = 7
fig = make_subplots(
rows=rows, cols=cols,
specs = [[{'type': 'choropleth'} for c in np.arange(cols)] for r in np.arange(rows)],
)
#Graph each state's data
for i, (date, df) in enumerate(death_counts_gbo):
fig.add_trace(go.Choropleth(
locations=df['State Abbr'], # Spatial coordinates
z = df['COVID-19 Deaths per 100k'].astype(float), # Data to be color-coded
locationmode = 'USA-states', # set of locations match entries in `locations`
colorscale = 'Reds',
zmin = 0,
zmax = 30,
colorbar_title = "Deaths per 100k",
text = date.strftime('%m-%d-%Y')
), row=i//7+1, col=i%7+1)
### This is where I'd like to set the subplot's title to 'date' ###
# Set title of entire figure
# Set each subplot map for the USA map instead of default world map
# Set each subplot map's lake color to light blue
fig.update_layout(
title_text = 'COVID-19 Deaths per 100k at week ending',
**{'geo' + str(i) + '_scope': 'usa' for i in [''] + np.arange(2,len(death_counts_gbo)+1).tolist()},
**{'geo' + str(i) + '_lakecolor': 'lightblue' for i in [''] + np.arange(2,len(death_counts_gbo)+1).tolist()},
)
fig.show()
编辑:对于我的示例,我可以在图形声明期间使用以下 kwarg 设置子图标题:
subplot_titles = [date.strftime('%m-%d-%Y') for date in list(death_counts_gbo.groups.keys())]
但是,为了我自己的启迪,如果我将来有更多涉及字幕确定的情况,我仍然想知道如何在循环期间/图形声明之后进行设置。
EDIT2:感谢@rpanai,我有一个解决方案,尽管它需要更改我的make_subplots 声明,除了循环中的单行。他告诉我,字幕是存储在fig.layout.annotations 中的注释,虽然可以提供字幕列表,但计算适当的x 和y 坐标可能很麻烦。我通过创建临时字幕并强制make_subplots 计算x 和y 坐标来解决这个问题。然后我更新了循环中的文本。
更新的make_subplots图形声明(添加了subplot_titles):
fig = make_subplots(
rows=rows, cols=cols,
specs = [[{'type': 'choropleth'} for c in np.arange(cols)] for r in np.arange(rows)],
subplot_titles = ['temp_subtitle' for date in np.arange(len(death_counts_gbo))]
)
单行(for循环的第一行):
fig.layout.annotations[i]['text'] = date.strftime('%m-%d-%Y')
【问题讨论】:
-
嗨 wex52,当您在
make_subplots中声明子图标题时,它们将存储为fig.layout.annotations我认为可以在 for 循环期间复制它创建一个annotations列表,但我不不认为值得为每个注释处理x和y位置。 -
谢谢你,@rpanai。我使用了您提供给我的信息,为您提出的问题编写了解决方法,并编辑了我的问题以包含我的解决方案。除了单行之外,我还需要在我的
make_subplots调用中添加一个临时字幕列表,以便它为我计算x和y的位置。 -
@rpanai 是对的。 # 使用 2x2 子图的随机名称初始化图形
figure_pl = make_subplots(rows=2, cols=2, start_cell="bottom-left", subplot_titles=("randname0","randname1","randname2", "randname3"))# Iteratively change the namesnew_names = [new_name0,new_name1,new_name2,new_name3]for i, new_name in enumerate(new_names):figure_pl.layout.annotations[i]["text"] = new_name -
@Arvind Kumar 这与 2021 年初的最新情节非常有效。要处理任何可能的未来 API 更改,请打印出
figure_pl.layout并查找定义上述条目的字典条目。
标签: python plotly subplot choropleth