Plotly Sunburst Chart (Python) - make_subplots 的 'specs' 参数必须是维度为 (1 x 1) 的二维字典列表

Plotly Sunburst Chart (Python) - 'specs' argument to make_subplots must be a 2D list of dictionaries with dimensions (1 x 1)

我正在使用 python Plotly(版本 5.1.0)构建 Sunburst 图表。

我一直在关注这里的教程:

https://plotly.com/python/sunburst-charts/#sunburst-chart-with-a-continuous-colorscale

具体来说,我正在尝试复制底部标题为 'Sunburst chart with a continuous colorscale' 的最后一个示例。

当我在本地 运行 时,一切正常。但是,当我尝试将其部署到我的服务器时,以下代码行会产生错误。

fig = make_subplots(1, 1, specs=[[{"type": "domain"}, {"type": "domain"}]],)

我收到以下 ValueError:

The 'specs' argument to make_subplots must be a 2D list of dictionaries with 
dimensions (1 x 1).

Received value of type <class 'list'>: [[{'type': 'domain'}, {'type': 'domain'}]]

我不确定为什么会收到此错误,因为我正在按照具有相同数据结构的示例进行操作。在本地效果很好。不知道是导入问题还是库冲突等问题

这是我的代码。

from plotly import graph_objs as go
from plotly.tools import make_subplots
import pandas as pd

df = pd.read_csv('../sunburst_pd.csv')

levels = ['PD', 'State', 'Region'] 
color_columns = ['BP', 'Black']
value_column = 'BP'

def build_hierarchical_dataframe(df, levels, value_column, color_columns=None):
    df_all_trees = pd.DataFrame(columns=['id', 'parent', 'value', 'color'])
    for i, level in enumerate(levels):
        df_tree = pd.DataFrame(columns=['id', 'parent', 'value', 'color'])
        dfg = df.groupby(levels[i:]).sum()
        dfg = dfg.reset_index()
        df_tree['id'] = dfg[level].copy()
        if i < len(levels) - 1:
            df_tree['parent'] = dfg[levels[i+1]].copy()
        else:
            df_tree['parent'] = 'total'
        df_tree['value'] = dfg[value_column]
        df_tree['color'] = dfg[color_columns[0]] / dfg[color_columns[1]]
        df_all_trees = df_all_trees.append(df_tree, ignore_index=True)
    total = pd.Series(dict(id='total', parent='',
                              value=df[value_column].sum(),
                              color=df[color_columns[0]].sum() / 
                              df[color_columns[1]].sum()))
    df_all_trees = df_all_trees.append(total, ignore_index=True)
    return df_all_trees

df_all_trees = build_hierarchical_dataframe(df, levels, value_column, 
    color_columns)
average_score = df['BP'].sum() / df['Black'].sum()

fig = make_subplots(1, 2, specs=[[{"type": "domain"}, {"type": "domain"}]],)

fig.add_trace(go.Sunburst(
    labels=df_all_trees['id'],
    parents=df_all_trees['parent'],
    values=df_all_trees['value'],
    branchvalues='total',
    marker=dict(
        colors=df_all_trees['color'],
        colorscale='RdBu',
        cmid=average_score),
    hovertemplate='<b>%{label} </b> <br> BP: %{value}<br> 
        BP Population: %. {color:.6f}',
    name=''
    ), 1, 1)

fig.add_trace(go.Sunburst(
    labels=df_all_trees['id'],
    parents=df_all_trees['parent'],
    values=df_all_trees['value'],
    branchvalues='total',
    marker=dict(
        colors=df_all_trees['color'],
        colorscale='RdBu',
        cmid=average_score),
    hovertemplate='<b>%{label} </b> <br> BP: %{value}<br> 
        BP Population: %{color:.6f}',
    maxdepth=2
    ), 1, 2)

fig.update_layout(margin=dict(t=10, b=10, r=10, l=10))

fig.show()

这是我的数据快照:

Region. |. State. | PD. |. BP.  |.  Black

South. |.Florida. |. FL. |. 3.  |. 1500
North. | New York. |.NY. |. 7. |.  1275

如有任何帮助,我们将不胜感激。

  • 据我从评论中了解到,您的主要目标是生成具有连续色标的朝阳轨迹
  • 使用plotly express做build sunburst
  • 的核心功能就简单多了
  • 这是一个简单的案例,使用所需的颜色方法更新轨迹
  • 您的示例数据非常简单...已添加另一行来演示此方法

示例数据

import pandas as pd
import io
df = pd.read_csv(io.StringIO("""Region|State|PD|BP|Black
South. |.Florida. |. FL. |3|1500
North. | New York. |.NY. |7|1275
South. |Texas|TX|5|750"""), sep="|", engine="python")

具有连续色阶的朝阳

import plotly.express as px
import numpy as np

# use plotly express to build the sunburst.  Insert a "Total" column into dataframe so
# center of sunburst is the total
fig = px.sunburst(
    df.assign(Total="Total"), path=["Total", "Region", "State"], values="BP"
)

# want a continuous colorscale.  Simplest way is to use trace built by px and update it...
fig.update_traces(
    marker={
        "colors": fig.data[0]["values"],
        "colorscale": "RdBu",
        "cmid": np.mean(fig.data[0]["values"]),
    }
)

输出