简体   繁体   中英

Plotly Subplots Value Error when Adding Trace

I am trying to add data to subplots with plotly and I keep running into a Value Error:

ValueError: 
    Invalid element(s) received for the 'data' property of 
        Invalid elements include: [Figure({
    'data': [{'hovertemplate': 'year=%{x}<br>value_sum=%{y}<extra></extra>',
              'legendgroup': '',
              'line': {'color': '#636efa', 'dash': 'solid'},
              'marker': {'symbol': 'circle'},
              'mode': 'lines',
              'name': '',
              'orientation': 'v',
              'showlegend': False,
              'type': 'scatter',
              'x': array(['2018', '2018', '2018', '2019', '2019', '2019', '2020', '2020', '2020',
                          '2021', '2021', '2021'], dtype=object),
              'xaxis': 'x',
              'y': array([1280, 1280, 1280,  747,  747,  747, 2596, 2596, 2596,  689,  689,  689],
                         dtype=int64),
              'yaxis': 'y'}],
    'layout': {'legend': {'tracegroupgap': 0},
               'margin': {'t': 60},
               'template': '...',
               'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title': {'text': 'year'}},
               'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'value_sum'}}}
})]
The 'data' property is a tuple of trace instances
that may be specified as:
  - A list or tuple of trace instances
    (e.g. [Scatter(...), Bar(...)])
  - A single trace instance
    (e.g. Scatter(...), Bar(...), etc.)
  - A list or tuple of dicts of string/value properties where:
    - The 'type' property specifies the trace type
        One of: ['bar', 'barpolar', 'box', 'candlestick',
                 'carpet', 'choropleth', 'choroplethmapbox',
                 'cone', 'contour', 'contourcarpet',
                 'densitymapbox', 'funnel', 'funnelarea',
                 'heatmap', 'heatmapgl', 'histogram',
                 'histogram2d', 'histogram2dcontour', 'icicle',
                 'image', 'indicator', 'isosurface', 'mesh3d',
                 'ohlc', 'parcats', 'parcoords', 'pie',
                 'pointcloud', 'sankey', 'scatter',
                 'scatter3d', 'scattercarpet', 'scattergeo',
                 'scattergl', 'scattermapbox', 'scatterpolar',
                 'scatterpolargl', 'scattersmith',
                 'scatterternary', 'splom', 'streamtube',
                 'sunburst', 'surface', 'table', 'treemap',
                 'violin', 'volume', 'waterfall']

    - All remaining properties are passed to the constructor of
      the specified trace type

    (e.g. [{'type': 'scatter', ...}, {'type': 'bar, ...}])

I have tried to convert the data to lists and tuples, but I still get this error. Further, when I simply plot the line without subplots, it works. I also tried switching to plotly.graph_objects, but it gave me some type of module error. The code is shown below:

from io import StringIO
import pandas as pd
import plotly.express as px

data='''
    Use-Cases   2018    2019    2020    2021
0   Consumer    50      251     2123    210
1   Education   541     52      32      23
2   Government  689     444     441     456
'''

df = pd.read_csv(StringIO(data), sep='\s+')

# Go from a wide to long dataframe using melt
df = pd.melt(df, id_vars=[ 'Use-Cases'], value_vars=['2018', '2019', '2020', '2021'])
df = df.rename(columns={ 'variable': 'year'})

# get totals for each year so the percent calculation can be done
aggregated_df = df[[ 'value', 'year']].groupby(['year']).agg(['sum']).reset_index()
aggregated_df.columns = ['year', 'value_sum']
df = pd.merge(df, aggregated_df, on=['year'], how='left')

# Caclulate percents and format the column
df['percent'] = (df['value']/df['value_sum']*100).round(1).astype(str) + "%"
df

fig = make_subplots(rows=1, cols=2)
fig.add_trace(px.line(df,df.year,df.value_sum))

The last line should be:

fig.add_trace(px.line(df,df.year,df.value_sum).data[0])
  • add_trace() adds a trace not a figure. px.line() returns a figure
  • .data is a list of traces, so [0] select first trace

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM