如何在 Plotly 中循环创建子图,其中每个子图上都有几条曲线?

2023-12-05

我已经在下面编写了嵌套循环来成功生成 21 个图表(例如,每个国家一个图表德国天然气 奥地利天然气公司)

dfs 是一个字典,以 21 个国家名称为键,以各自的储气 dfs 作为值

for country in list(dfs_storage.keys()):
    df_country=dfs_storage[country]
    month = list(set(df_country['month']))
    fig = go.Figure()
    for year in set(df_country['year']):
        workingGasVolume_peryear=df_country.loc[df_country['year']==year,'workingGasVolume']
        gasInStorage_peryear=df_country.loc[df_country['year']==year,'gasInStorage']
        # Create and style traces
        fig.add_trace(go.Scatter(x=month, y=workingGasVolume_peryear, name=f'workingGasVolume{year}',
                                 line=dict(width=4,dash='dash')))
        fig.add_trace(go.Scatter(x=month, y=gasInStorage_peryear, name=f'gasInStorage{year}',
                                 line = dict(width=4)))

    # Edit the layout
    fig.update_layout(title=f'{country} workingGasVolume gasInStorage',
                       xaxis_title='Month',
                       yaxis_title='Gas Volume')

    offline.plot({'data':fig},filename=f'{country} gas storage.html',auto_open=False)

现在我被要求将这 21 个图表放入一个 HTML 文件中,而不更改每个图表,例如它们可以一个接一个地垂直显示

我用下面的代码尝试了 Plotly 的“子图”,并修改了几次,但从未得到所需的图表,我得到了一个无用的图表,我看不到任何值。任何人都可以帮助我吗?谢谢

countries=[]
for country in list(dfs_storage.keys()):
    countries.append(country)
fig = make_subplots(
    rows=len(list(dfs_storage.keys())),cols=1,
    subplot_titles=(countries))

for country in countries:
    df_country=dfs_storage[country]
    month = list(set(df_country['month']))
    for year in set(df_country['year']):
        workingGasVolume_peryear=df_country.loc[df_country['year']==year,'workingGasVolume']
        gasInStorage_peryear=df_country.loc[df_country['year']==year,'gasInStorage']
        # Create and style traces
        fig.add_trace(go.Scatter(x=month, y=workingGasVolume_peryear, name=f'workingGasVolume{year}',
                                 line=dict(width=4,dash='dash')))
        fig.add_trace(go.Scatter(x=month, y=gasInStorage_peryear, name=f'gasInStorage{year}',
                                 line = dict(width=4)))

    # Edit the layout
# fig.update_layout(title='workingGasVolume gasInStorage',
#                    xaxis_title='Month',
#                    yaxis_title='Gas Volume')

offline.plot({'data':fig},filename='gas storage.html',auto_open=False) 

6 月 7 日编辑:根据 jayveesea 的建议,我在 add_trace 下添加了 row 和 col 参数,代码如下,但仍然有 Traceback:

countries=[]
for country in list(dfs_storage.keys()):
    countries.append(country)
fig = make_subplots(
    rows=len(list(dfs_storage.keys())),cols=1,
    subplot_titles=(countries))

for i in range(len(countries)):
    country=countries[i]
    df_country=dfs_storage[country]
    month = list(set(df_country['month']))
    for year in set(df_country['year']):
        workingGasVolume_peryear=df_country.loc[df_country['year']==year,'workingGasVolume']
        gasInStorage_peryear=df_country.loc[df_country['year']==year,'gasInStorage']
        # Create and style traces
        fig.add_trace(go.Scatter(x=month, y=workingGasVolume_peryear, name=f'workingGasVolume{year}',row=i,col=1,
                                 line=dict(width=4,dash='dash')))
        fig.add_trace(go.Scatter(x=month, y=gasInStorage_peryear, name=f'gasInStorage{year}',row=i,col=1,
                                 line = dict(width=4)))

    # Edit the layout
# fig.update_layout(title='workingGasVolume gasInStorage',
#                    xaxis_title='Month',
#                    yaxis_title='Gas Volume')

offline.plot({'data':fig},filename='gas storage.html',auto_open=False)

print('the Plotly charts are saved in the same folder as the Python code')

6月8日编辑: 这是我现在运行的代码,从@jayveesea的答案复制而来,仅修改了 df 的名称

countries=[]
for country in list(dfs_storage.keys()):
    countries.append(country)
# STEP 1
fig = make_subplots(
    rows=len(countries), cols=1,
    subplot_titles=(countries))

for i, country in enumerate(countries): #enumerate here to get access to i
    years = df_country.year[df_country.country==country].unique()
    for yrs in years:
        focus = (df_country.country==country) & (df_country.year==yrs)
        month = df_country.month[focus]
        workingGasVolume_peryear = df_country.workingGasVolume[focus]
        gasInStorage_peryear = df_country.gasInStorage[focus]

        # STEP 2, notice position of arguments!
        fig.add_trace(go.Scatter(x=month, 
                                 y=workingGasVolume_peryear, 
                                 name=f'workingGasVolume{yrs}',
                                 line=dict(width=4,dash='dash')),
                      row=i+1, #index for the subplot, i+1 because plotly starts with 1
                      col=1)
        fig.add_trace(go.Scatter(x=month, 
                                 y=gasInStorage_peryear, 
                                 name=f'gasInStorage{yrs}',
                                 line = dict(width=4)),
                      row=i+1,
                      col=1)      
fig.show()

但我仍然有回溯消息

Traceback (most recent call last):

  File "<ipython-input-27-513826172e49>", line 43, in <module>
    line=dict(width=4,dash='dash')),

TypeError: 'dict' object is not callable

要在绘图中使用子图,您需要:

  1. use make_subplots初始化指定的布局row and column
  2. 然后使用row and col作为参数fig.add_trace。注意:子图行和列从 1(不是零)开始

就您而言,步骤2是您陷入困境的地方。最初这部分丢失了(第一篇文章),但现在在您的更新中它被添加为参数go.Scatter。仔细看过去这里的例子因为区别只是逗号和括号及其位置。

为了澄清这一点:

fig.add_trace(go.Scatter(x=month, 
                         y=workingGasVolume_peryear, 
                         name=f'workingGasVolume{year}',
                         row=i,
                         col=1,
                         line=dict(width=4,dash='dash')))

应该:

fig.add_trace(go.Scatter(x=month, 
                         y=workingGasVolume_peryear, 
                         name=f'workingGasVolume{year}',
                         line=dict(width=4,dash='dash')),
              row=i+1,
              col=1)

我对你的代码和数据有困难,这可能是我的问题,因为我不使用这样的字典,但这里有一个工作示例,其中包含 csv 中的数据以及使用pandas。另外,我将其中一年更改为不同的国家,以便有另一个情节。

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

df = pd.read_csv('someData.csv')
countries = df.country.unique()

# STEP 1
fig = make_subplots(
    rows=len(countries), cols=1,
    subplot_titles=(countries))

for i, country in enumerate(countries): #enumerate here to get access to i
    years = df.year[df.country==country].unique()
    for yrs in years:
        focus = (df.country==country) & (df.year==yrs)
        month = df.month[focus]
        workingGasVolume_peryear = df.workingGasVolume[focus]
        gasInStorage_peryear = df.gasInStorage[focus]

        # STEP 2, notice position of arguments!
        fig.add_trace(go.Scatter(x=month, 
                                 y=workingGasVolume_peryear, 
                                 name=f'workingGasVolume{yrs}',
                                 line=dict(width=4,dash='dash')
                                ),
                      row=i+1, #index for the subplot, i+1 because plotly starts with 1
                      col=1)
        fig.add_trace(go.Scatter(x=month, 
                                 y=gasInStorage_peryear, 
                                 name=f'gasInStorage{yrs}',
                                 line = dict(width=4)),
                      row=i+1,
                      col=1)      
fig.show()

enter image description here

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Plotly 中循环创建子图,其中每个子图上都有几条曲线? 的相关文章

随机推荐

  • 有没有“单项大小的异步任务缓冲区”这样的同步工具?

    在 UI 开发中 我多次以这样的方式处理事件 当事件第一次出现时 我立即开始处理 但如果有一个处理操作正在进行中 我会等待它完成 然后再处理另一个事件 如果在操作完成之前发生多个事件 我只处理最近的一个 我通常的做法是 我的处理方法有一个循
  • 如何允许 Java 客户端 TLS10 连接?

    在尝试使用 Java 16 在 Eclipse 中执行 hello world MSSQL JDBC 连接时 出现以下错误 server selected protocol version TLS10 is not accepted by
  • 如何将mongodb文档中的所有数组元素更改为某个值? [复制]

    这个问题在这里已经有答案了 假设我有以下文档 id ObjectId 5234cc89687ea597eabee675 code xyz tags school book bag headphone appliance qty size S
  • 从aspx网页读取xml

    我们必须从 aspx 页面读取数据 当我们使用查询字符串调用页面时 它会返回一个 xml 文档 其中包含与查询字符串匹配的数据 我们有一个与我们返回的 xml 相匹配的 XSD 我想我们可以从http响应中读取xml文档 这行得通吗 我们怎
  • 从服务访问 UI 线程处理程序

    我正在 Android 上尝试一些新的东西 我需要访问 UI 线程的处理程序 我知道以下几点 UI线程有自己的处理程序 和活套 任何消息都会被放置 进入UI的消息队列 线 Looper 获取事件 并将其传递给处理程序 处理程序处理消息并 将
  • 确保 MATLAB 不会重新计算符号表达式

    我正在构建 我的第一个 MatLab 程序 它需要对方程进行符号微分 然后多次使用此解决方案 使用不同的数字输入 我不希望它每次需要输入一组新的数值时都重新计算符号微分 这可能会大大增加运行该程序所需的时间 鉴于其本质 数字优化器 这可能已
  • MPDF 电子邮件附件发送空白 PDF

    我已经使用 mpdf 成功生成了 PDF 我已通过下载 PDF 进行了验证 但是 当我将 PDF 作为电子邮件附件发送时 我收到 Adob e Reader 的空白 PDF 并显示 内存不足 错误 下面是我的代码
  • 为什么 dart 错误地推断出我的泛型参数类型?

    当我明确地将 mySet 变量等同于 int 集文字时 我似乎无法理解为什么 mySet 变量被推断为具有动态参数类型的通用集 那么这个结果合乎逻辑吗 还是 dart 确实未能推断出泛型集参数类型 main Set mySet 1 2 3
  • Xamarin + Android + 绑定 YouTube 视频播放器编译错误

    我希望将 YouTubeAndroidPlayerApi jar 绑定到我的 Xamarin Android 项目中 我已在 Jars 文件夹下添加了 YouTubeAndroidPlayerApi jar 但我的项目无法编译 错误 不要覆
  • 仅通过意图共享到 LinkedIn 的类名称

    我目前正在 Android 应用程序中为精选的流行平台创建直接意图以共享一些文本 我目前正在尝试获得与 LinkedIn 合作的直接意向 我目前有一个为 Twitter 工作的直接意图 如下所示 shareIntent new Intent
  • 在 Eclipse 中运行单个 JUnit 测试

    如果我有一个包含多个测试的测试套件 当我尝试从代码编辑器的上下文菜单或 JUnit 视图运行单个单元测试时 它似乎坚持始终运行整个套件 而不是单次测试 有没有办法禁用更改此行为 以便我可以要求运行该测试 并且仅运行该测试 在包资源管理器中展
  • 我无法让这个 mysql join 查询产生所需的结果

    三个表的结构 Booking CREATE TABLE booking bookingID int 11 NOT NULL AUTO INCREMENT receipt no int 11 NOT NULL client varchar 3
  • 无法隐式初始化 std::function

    我编写了这个函子来执行and手术 unary functor performs template
  • 将只读docker卷的变化反映到容器中?

    我有一个配置文件在运行时使用只读卷注入到 Docker 中 因此容器无法更改配置文件的内容 但主机可以 这个想法是向容器内的进程发送 SIGHUB 以重新加载任何配置更改 然而 Docker 似乎无法检测到配置文件的任何更改 并且似乎看到了
  • 工具栏在 RecyclerView 滚动条上留下空白并隐藏

    我试图在 RecyclerView 滚动条上隐藏我的工具栏 到目前为止它似乎已经隐藏了 但它留下了一个白色的空白 我很确定这与我的 MainActivity 布局和 FrameLayout 中的片段的叠加有关 这是我的activity ma
  • @OneToMany List<> 与 Set<> 区别

    如果我使用的话有什么区别吗 OneToMany public Set
  • 在 OS X 上保留内存

    相当于 Windows 的是什么VirtualAlloc在 OS X 中 也就是说 我如何保留一个连续的地址空间而不实际提交它 然后稍后提交它的块 Thanks Alex The mmap 函数 调用MAP ANON MAP PRIVATE
  • Chrome 扩展程序可在显示文本之前替换网页和 Facebook 帖子中的文本

    我正在开发一个 Chrome 扩展程序 它可以替换网页文本中的指定字符串或正则表达式 总体来说效果很好 但有两个问题我想解决 1 在文本替换发生之前 显示原始的 未更改的网页文本 2 文本替换不会影响滚动到页面底部后动态加载的 Facebo
  • 当我使用 JavaScript Fetch API 发送多部分表单数据时,FastAPI 返回“错误 422:无法处理的实体”

    在发送一些简单的内容时 我在使用 Fetch API JavaScript 方法时遇到一些问题formData像这样 function register var formData new FormData var textInputName
  • 如何在 Plotly 中循环创建子图,其中每个子图上都有几条曲线?

    我已经在下面编写了嵌套循环来成功生成 21 个图表 例如 每个国家一个图表德国天然气 奥地利天然气公司 dfs 是一个字典 以 21 个国家名称为键 以各自的储气 dfs 作为值 for country in list dfs storag