【问题标题】:How do I set each plotly subplot title during graph creation loop?如何在图形创建循环期间设置每个情节子图标题?
【发布时间】: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 names new_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


【解决方案1】:

您提到您希望能够编辑标题(即注释)之后您也构建了您的图形。如果您已经有了 一些 标题,并且想要更改它们,您可以将 fig.for_each_annotation() 与这样的 dict 结合使用:

names = {'Plot 1':'2016', 'Plot 2':'2017', 'Plot 3':'2018', 'Plot 4':'2019'}
fig.for_each_annotation(lambda a: a.update(text = names[a.text]))

这会变成这样:

进入这个:

您还可以轻松地将现有标题与您选择的附加标题结合起来:

fig.for_each_annotation(lambda a: a.update(text = a.text + ': ' + names[a.text]))

情节 3

完整代码:

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

fig = make_subplots(
    rows=2, cols=2,
    subplot_titles=("Plot 1", "Plot 2", "Plot 3", "Plot 4"))


fig.add_trace(go.Scatter(x=[1, 2, 3], y=[4, 5, 6]),
              row=1, col=1)

fig.add_trace(go.Scatter(x=[20, 30, 40], y=[50, 60, 70]),
              row=1, col=2)

fig.add_trace(go.Scatter(x=[300, 400, 500], y=[600, 700, 800]),
              row=2, col=1)

fig.add_trace(go.Scatter(x=[4000, 5000, 6000], y=[7000, 8000, 9000]),
              row=2, col=2)

fig.update_layout(height=500, width=700,
                  title_text="Multiple Subplots with Titles")

names = {'Plot 1':'2016', 'Plot 2':'2017', 'Plot 3':'2018', 'Plot 4':'2019'}

# fig.for_each_annotation(lambda a: a.update(text = names[a.text]))

fig.for_each_annotation(lambda a: a.update(text = a.text + ': ' + names[a.text]))
         
fig.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-06
    • 1970-01-01
    • 2019-04-09
    • 1970-01-01
    • 2020-06-29
    • 2020-09-25
    • 1970-01-01
    • 2020-10-14
    相关资源
    最近更新 更多