ValueError:为“数据”属性接收到无效元素

bar*_*mon 6 python plotly

我遇到了 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]
Run Code Online (Sandbox Code Playgroud)

然后,我创建了一个 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()
Run Code Online (Sandbox Code Playgroud)

这导致了以下错误:

---------------------------------------------------------------------------
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, ...}])
Run Code Online (Sandbox Code Playgroud)

我不知道做错了什么。奇怪的是,我的数据看起来形状正确,因为我可以毫无问题地运行以下代码:

fig = go.Figure(data1)
fig.show()
Run Code Online (Sandbox Code Playgroud)

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

谢谢!

Gui*_*cia 6

您收到错误的原因是因为该函数append_trace()期望以您声明的形式出现单个跟踪。然而,图形对象Figure具有这样的功能add_traces(),您可以使用该功能将数据参数作为具有多个跟踪的列表进行传递。因此,我建议两个简单的解决方案:

解决方案 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()
Run Code Online (Sandbox Code Playgroud)

解决方案 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()
Run Code Online (Sandbox Code Playgroud)


I A*_*nko 6

我的问题是我试图在跟踪中使用 px (plotly express)绘图。我发现问题是 px 返回一个完整的数字,但 add_trace (add_traces,append_trace)只需要 data

为我解决这个问题的方法是将“.data[0]”添加到我的 px 图形名称的末尾:

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()
Run Code Online (Sandbox Code Playgroud)

或者,如果您使用 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()
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助某人节省时间。