python ValueError:收到'data'属性的无效元素

dl5txlt9  于 2022-12-02  发布在  Python
关注(0)|答案(4)|浏览(228)

我遇到了一个问题与plotly。我想显示不同的数字,但不知何故,我不能管理实现我想要的。
我创建了2个数据源:

from plotly.graph_objs.scatter import Line
import plotly.graph_objs as go

trace11 = go.Scatter(
    x = [0, 1, 2],
    y = [0, 0, 0],
    line = Line({'color': 'rgb(0, 0, 128)', 'width': 1})
)

trace12 = go.Scatter(
    x=[0, 1, 2],
    y=[1, 1, 1],
    line = Line({'color': 'rgb(128, 0, 0)', 'width': 1})
)

trace21 = go.Scatter(
    x = [0, 1, 2],
    y = [0.5, 0.5, 0.5],
    line = Line({'color': 'rgb(0, 0, 128)', 'width': 1})
)

trace22 = go.Scatter(
    x=[0, 1, 2],
    y=[1.5, 1.5, 1.5],
    line = Line({'color': 'rgb(128, 0, 0)', 'width': 1})
)

data1 = [trace11, trace12]
data2 = [trace21, trace22]

然后,我创建了一个具有1行和2列的子图,并尝试将此数据添加到子图中:

from plotly import tools
fig = tools.make_subplots(rows=1, cols=2)
fig.append_trace(data1, 1, 1)
fig.append_trace(data2, 1, 2)
fig.show()

这导致了以下错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-6-ba20e4900d41> in <module>
      1 from plotly import tools
      2 fig = tools.make_subplots(rows=1, cols=2)
----> 3 fig.append_trace(data1, 1, 1)
      4 fig.append_trace(data2, 1, 2)
      5 fig.show()

~\Anaconda3\lib\site-packages\plotly\basedatatypes.py in append_trace(self, trace, row, col)
   1797         )
   1798 
-> 1799         self.add_trace(trace=trace, row=row, col=col)
   1800 
   1801     def _set_trace_grid_position(self, trace, row, col, secondary_y=False):

~\Anaconda3\lib\site-packages\plotly\basedatatypes.py in add_trace(self, trace, row, col, secondary_y)
   1621             rows=[row] if row is not None else None,
   1622             cols=[col] if col is not None else None,
-> 1623             secondary_ys=[secondary_y] if secondary_y is not None else None,
   1624         )
   1625 

~\Anaconda3\lib\site-packages\plotly\basedatatypes.py in add_traces(self, data, rows, cols, secondary_ys)
   1684 
   1685         # Validate traces
-> 1686         data = self._data_validator.validate_coerce(data)
   1687 
   1688         # Set trace indexes

~\Anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in validate_coerce(self, v, skip_invalid)
   2667 
   2668             if invalid_els:
-> 2669                 self.raise_invalid_elements(invalid_els)
   2670 
   2671             v = to_scalar_or_list(res)

~\Anaconda3\lib\site-packages\_plotly_utils\basevalidators.py in raise_invalid_elements(self, invalid_els)
    296                     pname=self.parent_name,
    297                     invalid=invalid_els[:10],
--> 298                     valid_clr_desc=self.description(),
    299                 )
    300             )

ValueError: 
    Invalid element(s) received for the 'data' property of 
        Invalid elements include: [[Scatter({
    'line': {'color': 'rgb(0, 0, 128)', 'width': 1}, 'x': [0, 1, 2], 'y': [0, 0, 0]
}), Scatter({
    'line': {'color': 'rgb(128, 0, 0)', 'width': 1}, 'x': [0, 1, 2], 'y': [1, 1, 1]
})]]

    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: ['area', 'bar', 'barpolar', 'box',
                     'candlestick', 'carpet', 'choropleth',
                     'choroplethmapbox', 'cone', 'contour',
                     'contourcarpet', 'densitymapbox', 'funnel',
                     'funnelarea', 'heatmap', 'heatmapgl',
                     'histogram', 'histogram2d',
                     'histogram2dcontour', 'image', 'indicator',
                     'isosurface', 'mesh3d', 'ohlc', 'parcats',
                     'parcoords', 'pie', 'pointcloud', 'sankey',
                     'scatter', 'scatter3d', 'scattercarpet',
                     'scattergeo', 'scattergl', 'scattermapbox',
                     'scatterpolar', 'scatterpolargl',
                     '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, ...}])

我可能做错了什么。奇怪的是,我的数据看起来是正确的,因为我可以运行下面的代码没有任何问题:

fig = go.Figure(data1)
fig.show()

我希望你能帮我找到解决的办法。
谢谢你!

eh57zj3b

eh57zj3b1#

之所以会出现错误,是因为函数append_trace()期望的是一个单一的跟踪,其形式与您声明的跟踪相同。然而,图形对象 Figure 有函数add_traces(),通过该函数,您可以将 data 参数作为包含多个跟踪的列表进行传递。因此,我建议两个简单的解决方案:

解决方案1:单独追加跟踪

from plotly.graph_objs.scatter import Line
import plotly.graph_objs as go
trace11 = go.Scatter(x = [0, 1, 2], y = [0, 0, 0],  line = Line({'color': 'rgb(0, 0, 128)', 'width': 1}))
trace12 = go.Scatter(x = [0, 1, 2], y = [1, 1, 1], line = Line({'color': 'rgb(128, 0, 0)', 'width': 1}))
trace21 = go.Scatter(x = [0, 1, 2], y = [0.5, 0.5, 0.5], line = Line({'color': 'rgb(0, 0, 128)', 'width': 1}))
trace22 = go.Scatter(x = [0, 1, 2], y = [1.5, 1.5, 1.5], line = Line({'color': 'rgb(128, 0, 0)', 'width': 1}))

from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2)
fig.append_trace(trace11, row=1, col=1)
fig.append_trace(trace12, row=1, col=1)
fig.append_trace(trace21, row=1, col=2)
fig.append_trace(trace22, row=1, col=2)
fig.show()

解决方案2:请改用函数add_traces(data,rows,cols)

from plotly.graph_objs.scatter import Line
import plotly.graph_objs as go
trace11 = go.Scatter(x = [0, 1, 2], y = [0, 0, 0], line = Line({'color': 'rgb(0, 0, 128)', 'width': 1}))
trace12 = go.Scatter(x = [0, 1, 2], y = [1, 1, 1], line = Line({'color': 'rgb(128, 0, 0)', 'width': 1}))
trace21 = go.Scatter(x = [0, 1, 2], y = [0.5, 0.5, 0.5], line = Line({'color': 'rgb(0, 0, 128)', 'width': 1}))
trace22 = go.Scatter(x = [0, 1, 2], y = [1.5, 1.5, 1.5], line = Line({'color': 'rgb(128, 0, 0)', 'width': 1}))

from plotly.subplots import make_subplots
fig = make_subplots(rows=1, cols=2)
data1 = [trace11, trace12]
data2 = [trace21, trace22]
fig.add_traces(data1, rows=1, cols=1)
fig.add_traces(data2, rows=1, cols=2)
fig.show()
7qhs6swi

7qhs6swi2#

我自己也遇到了类似的问题,而做的交互式Python Jmeter 板与Plotly和Dash Udemy课程,并找到了如何让我的代码工作,所以我会张贴我的有问题的代码和什么结束了为我工作,以便您可以比较。请记住,我不是一个程序员或计算机科学家的贸易,所以我不能提供所有的来龙去脉,在幕后发生了什么...还有,我在检查你的代码时,发现我们都传入了列表,而其他为append_trace()调用工作的代码却没有传入列表。我希望这能有所帮助。
首先,根据我对这个问题的研究,tools.make_subplots()被弃用,并且在我的代码中没有使用从plotly导入工具。我认为您需要用途:

from plotly.subplots import make_subplots

接下来,我想我只是在不合适的地方使用了一个列表。下面是我的原始代码,它不起作用:

import plotly.offline as pyo
import plotly.graph_objs as go
from plotly import tools
from plotly.subplots import make_subplots
import pandas as pd

df1 = pd.read_csv('Data/2010SantaBarbaraCA.csv')
df2 = pd.read_csv('Data/2010YumaAZ.csv')
df3 = pd.read_csv('Data/2010SitkaAK.csv')

trace1 = [go.Heatmap(x=df1['DAY'],
                   y=df1['LST_TIME'],
                   z=df1['T_HR_AVG'].values.tolist(),
                     zmin=5,
                     zmax=40)]  # z= cannot accept a pandas column, needs to be a list

trace2 = [go.Heatmap(x=df2['DAY'],
                   y=df2['LST_TIME'],
                   z=df2['T_HR_AVG'].values.tolist(),
                     zmin=5,
                     zmax=40)]  # z= cannot accept a pandas column, needs to be a list

trace3 = [go.Heatmap(x=df3['DAY'],
                   y=df3['LST_TIME'],
                   z=df3['T_HR_AVG'].values.tolist(),
                     zmin=5,
                     zmax=40)]  # z= cannot accept a pandas column, needs to be a list

# fig = tools.make_sublots(rows=1,
#                          columns=3,
#                          subplot_titles=['Santa Barbara CA','Yuma AZ', 'Sitka AK'],
#                          shared_yaxes=True)

fig = make_subplots(rows=1,
                cols=3,
                subplot_titles=['Santa Barbara CA', 'Yuma AZ', 'Sitka AK'],
                shared_yaxes=True)

# fig.append_trace(trace#, row#, column#)
fig.append_trace(trace1, row=1, col=1)
fig.append_trace(trace2, row=1, col=2)
fig.append_trace(trace3, row=1, col=3)

# data = [trace1, trace2, trace3]

# layout = go.Layout(title='Santa Barbara California Temperatures')

pyo.plot(fig)

请注意,我用括号定义了跟踪#

trace1 = [go.Heatmap(x=df1['DAY'],
                   y=df1['LST_TIME'],
                   z=df1['T_HR_AVG'].values.tolist(),
                     zmin=5,
                     zmax=40)]

当我从每个跟踪声明中去掉括号后,我的代码就可以工作了。下面是我的代码:

import plotly.offline as pyo
import plotly.graph_objs as go
from plotly import tools
from plotly.subplots import make_subplots
import pandas as pd

df1 = pd.read_csv('Data/2010SantaBarbaraCA.csv')
df2 = pd.read_csv('Data/2010YumaAZ.csv')
df3 = pd.read_csv('Data/2010SitkaAK.csv')

trace1 = go.Heatmap(x=df1['DAY'],
                   y=df1['LST_TIME'],
                   z=df1['T_HR_AVG'].values.tolist(),
                     zmin=5,
                     zmax=40)  # z= cannot accept a pandas column, needs to be a list

trace2 = go.Heatmap(x=df2['DAY'],
                   y=df2['LST_TIME'],
                   z=df2['T_HR_AVG'].values.tolist(),
                     zmin=5,
                     zmax=40)  # z= cannot accept a pandas column, needs to be a list

trace3 = go.Heatmap(x=df3['DAY'],
                   y=df3['LST_TIME'],
                   z=df3['T_HR_AVG'].values.tolist(),
                     zmin=5,
                     zmax=40)  # z= cannot accept a pandas column, needs to be a list

# fig = tools.make_sublots(rows=1,
#                          columns=3,
#                          subplot_titles=['Santa Barbara CA','Yuma AZ', 'Sitka AK'],
#                          shared_yaxes=True)

fig = make_subplots(rows=1,
                    cols=3,
                    subplot_titles=['Santa Barbara CA', 'Yuma AZ', 'Sitka AK'],
                    shared_yaxes=True)

# fig.append_trace(trace#, row#, column#)
fig.append_trace(trace1, row=1, col=1)
fig.append_trace(trace2, row=1, col=2)
fig.append_trace(trace3, row=1, col=3)

# data = [trace1, trace2, trace3]

# layout = go.Layout(title='Santa Barbara California Temperatures')

pyo.plot(fig)

我知道您使用的是分散图,而我使用的是热图,但我认为您的问题可能是(除了使用make_subplots()工具之外),您正在将data1和data2传递到append_trace()呼叫列表,我不认为append_trace()调用就像这样。我建议不要向append_trace传递列表()调用,看看是否有效。如果有效,那么你可能需要调整你的数据变量,使其不被列出,然后从那里开始。我希望这对你有帮助。

gwo2fgha

gwo2fgha3#

在尝试制作直方图的子图时,我遇到了一个类似的问题。我的错误发生在我尝试以错误的方式进行循环时,但下面的解决方案解决了您遇到的问题。我使用add_trace代替append_trace,并使用for loop以便于将来使用。

from plotly.graph_objs.scatter import Line
from plotly.subplots import make_subplots
import plotly.graph_objs as go

trace11 = go.Scatter(
    x = [0, 1, 2],
    y = [0, 0, 0],
    line = Line({'color': 'rgb(0, 0, 128)', 'width': 1})
)

trace12 = go.Scatter(
    x=[0, 1, 2],
    y=[1, 1, 1],
    line = Line({'color': 'rgb(128, 0, 0)', 'width': 1})
)

trace21 = go.Scatter(
    x = [0, 1, 2],
    y = [0.5, 0.5, 0.5],
    line = Line({'color': 'rgb(0, 0, 128)', 'width': 1})
)

trace22 = go.Scatter(
    x=[0, 1, 2],
    y=[1.5, 1.5, 1.5],
    line = Line({'color': 'rgb(128, 0, 0)', 'width': 1})
)
trace=[trace11, trace12, trace21, trace22]

plot_rows=2
plot_cols=2
fig = make_subplots(rows=plot_rows, cols=plot_cols)

x=0
for i in range(1, plot_rows + 1):
    for j in range(1, plot_cols + 1):
        fig.add_trace(trace[x],
                     row=i,
                     col=j)
        x+=1

fig.update_layout(height=600, width=600)
fig.show()
h79rfbju

h79rfbju4#

我的问题是,我试图在trace中使用px(plotly express)绘图。我发现,问题是px返回一个完整的图形,而add_trace(add_traces,append_trace)想要的 * 只是数据 *。
解决这个问题的方法是在px图名的末尾添加“.data[0]”:

fig = go.Figure()
df = pd.DataFrame({'x':[1,2,3,4], 'y':[5,6,7,8]})
fig2 = px.scatter(df, x="x", y="y")
fig.add_trace(fig2.data[0])
fig.show()

或者,如果使用add_traces(复数),则不需要[0]限定符。

fig = go.Figure()
df = pd.DataFrame({'x':[1,2,3,4], 'y':[5,6,7,8]})
fig2 = px.scatter(df, x="x", y="y")
fig.add_traces(fig2.data)
fig.show()

希望这能帮助某人保存时间。

相关问题