【发布时间】:2021-06-17 06:23:54
【问题描述】:
我想画各种各样的立方体, 所以引用了以下链接:
SAMPLE1:https://plotly.com/python/3d-mesh/#mesh-cube
示例 2:https://plotly.com/python/3d-subplots/#3d-surface-subplots
接口:https://plotly.com/python-api-reference/generated/plotly.subplots.make_subplots.html
稍作改动以从 json 获取 x,y,z 位置参数。
然后在下面写代码。为什么不工作并提前感谢。
import plotly.graph_objects as go
import pandas as pd
import numpy as np
import json
import math
import os
from plotly.subplots import make_subplots
# SET CONFIG OF FIGURE
def config(r,c):
for idx, (id,x,y,z) in enumerate(zip(_i, _x, _y, _z)):
# DRAW A CUBE
chunk = go.Figure(data=[
go.Mesh3d(
x=[0.0, 0.0, x, x, 0.0, 0.0, x, x],
y=[0.0, y, y, 0.0, 0.0, y, y, 0.0],
z=[0.0, 0.0, 0.0, 0.0, z, z, z, z],
intensity = np.linspace(0, 1, 8, endpoint=True),
intensitymode = 'cell',
i = [7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2],
j = [3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3],
k = [0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6],
showscale=False
)])
# APPEND THE CUBE
fig.add_trace(chunk, row=r, col=c)
if __name__ == "__main__":
# LOAD DATA
in1 = "data.json"
with open(in1, mode='r', encoding='utf-8_sig') as f:
_df = json.load(f)
df = pd.DataFrame(_df)
# READ ID,X,Y,Z FROM DATAFRAME
_i = df.iloc[:, 0]
_x = df.iloc[:, 2]
_y = df.iloc[:, 3]
_z = df.iloc[:, 4]
specs = []
# SET SUBPLOT POSITION CLOSEST TO SQUARE
rows = round(len(_i) **(1/2))
cols = rows + math.ceil((len(_i)%rows)/rows)
for r in range(rows):
_ = []
for c in range(cols):
_ += [{'type': 'mesh3d'}]
specs += [_]
fig = make_subplots(rows=rows, cols=cols,specs=specs)
for r in range(rows):
for c in range(cols):
config(r,c)
# DRAW ALL CUBES
fig.show()
错误:
--------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-7-ff653a5829ea> in <module>
17 for r in range(rows):
18 for c in range(cols):
---> 19 config(r,c)
20 fig.show()
<ipython-input-6-30b9398571d7> in config(r, c)
23 )
24
---> 25 fig.add_trace(chunk, row=r, col=c)
~/.anyenv/envs/pyenv/versions/3.7.5/lib/python3.7/site-packages/plotly/basedatatypes.py in add_trace(self, trace, row, col, secondary_y, exclude_empty_subplots)
2102 cols=[col] if col is not None else None,
2103 secondary_ys=[secondary_y] if secondary_y is not None else None,
-> 2104 exclude_empty_subplots=exclude_empty_subplots,
2105 )
2106
~/.anyenv/envs/pyenv/versions/3.7.5/lib/python3.7/site-packages/plotly/basedatatypes.py in add_traces(self, data, rows, cols, secondary_ys, exclude_empty_subplots)
2181
2182 # Validate traces
-> 2183 data = self._data_validator.validate_coerce(data)
2184
2185 # Set trace indexes
~/.anyenv/envs/pyenv/versions/3.7.5/lib/python3.7/site-packages/_plotly_utils/basevalidators.py in validate_coerce(self, v, skip_invalid, _validate)
2675
2676 if invalid_els:
-> 2677 self.raise_invalid_elements(invalid_els)
2678
2679 v = to_scalar_or_list(res)
~/.anyenv/envs/pyenv/versions/3.7.5/lib/python3.7/site-packages/_plotly_utils/basevalidators.py in raise_invalid_elements(self, invalid_els)
300 pname=self.parent_name,
301 invalid=invalid_els[:10],
--> 302 valid_clr_desc=self.description(),
303 )
304 )
ValueError:
Invalid element(s) received for the 'data' property of
Invalid elements include: [Figure({
'data': [{'i': [7, 0, 0, 0, 4, 4, 6, 6, 4, 0, 3, 2],
'intensity': array([0. , 0.14285714, 0.28571429, 0.42857143, 0.57142857, 0.71428571,
0.85714286, 1. ]),
'intensitymode': 'cell',
'j': [3, 4, 1, 2, 5, 6, 5, 2, 0, 1, 6, 3],
'k': [0, 7, 2, 3, 6, 7, 1, 1, 5, 5, 7, 6],
'showscale': False,
'type': 'mesh3d',
'x': [0.0, 0.0, 0.7, 0.7, 0.0, 0.0, 0.7, 0.7],
'y': [0.0, 1.11, 1.11, 0.0, 0.0, 1.11, 1.11, 0.0],
'z': [0.0, 0.0, 0.0, 0.0, 0.65, 0.65, 0.65, 0.65]}],
'layout': {'height': 400, 'template': '...', 'title': {'text': 'NO.3488', 'x': 0.5, 'y': 0.55}, 'width': 400}
})]
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, ...}])
【问题讨论】:
-
这一行:
cols = row + math.ceil((len(_i)%row)/row)->row未定义。 -
@EricLavault 感谢您的指出。我修复了它然后得到了我一直遇到的错误。
标签: python plotly mesh subplot