@@ -118,29 +118,63 @@ class Grid(MutableSequence):
118
118
py.plot([trace], filename='graph from grid')
119
119
```
120
120
"""
121
- def __init__ (self , iterable_of_columns ):
121
+ def __init__ (self , columns_or_json ):
122
122
"""
123
- Initialize a grid with an iterable of
124
- `plotly.grid_objs.Column objects
123
+ Initialize a grid with an iterable of `plotly.grid_objs.Column`
124
+ objects or a json/dict describing a grid. See second usage example
125
+ below for the necessary structure of the dict.
125
126
126
- Usage example :
127
+ Example from iterable of columns :
127
128
```
128
129
column_1 = Column([1, 2, 3], 'time')
129
130
column_2 = Column([4, 2, 5], 'voltage')
130
131
grid = Grid([column_1, column_2])
131
132
```
133
+ Example from json grid
134
+ ```
135
+ grid_json = {
136
+ 'cols': {
137
+ 'time': {'data': [1, 2, 3], 'order': 0, 'uid': '4cd7fc'},
138
+ 'voltage': {'data': [4, 2, 5], 'order': 1, 'uid': u'2744be'}
139
+ }
140
+ }
141
+ grid = Grid(grid_json)
142
+ ```
132
143
"""
133
144
134
145
# TODO: verify that columns are actually columns
135
-
136
- column_names = [column .name for column in iterable_of_columns ]
137
- duplicate_name = utils .get_first_duplicate (column_names )
138
- if duplicate_name :
139
- err = exceptions .NON_UNIQUE_COLUMN_MESSAGE .format (duplicate_name )
140
- raise exceptions .InputError (err )
141
-
142
- self ._columns = list (iterable_of_columns )
143
- self .id = ''
146
+ if isinstance (columns_or_json , (list , tuple )):
147
+ column_names = [column .name for column in columns_or_json ]
148
+ duplicate_name = utils .get_first_duplicate (column_names )
149
+ if duplicate_name :
150
+ err = exceptions .NON_UNIQUE_COLUMN_MESSAGE .format (duplicate_name )
151
+ raise exceptions .InputError (err )
152
+
153
+ self ._columns = list (columns_or_json )
154
+ self .id = ''
155
+ elif isinstance (columns_or_json , dict ):
156
+ # check if 'cols' is only root key
157
+ if 'cols' not in columns_or_json :
158
+ raise exceptions .PlotlyError (
159
+ "'cols' must be the one and only key in your json grid."
160
+ )
161
+
162
+ # check if 'data', 'order' and 'uid' are not in columns
163
+ grid_col_keys = ['data' , 'order' , 'uid' ]
164
+
165
+ for column_name in columns_or_json ['cols' ]:
166
+ for key in grid_col_keys :
167
+ if key not in columns_or_json ['cols' ][column_name ]:
168
+ raise exceptions .PlotlyError (
169
+ "Each column name of your dictionary must have "
170
+ "'data', 'order' and 'uid' as keys."
171
+ )
172
+
173
+ self ._columns = [Column (columns_or_json ['cols' ][column_name ]['data' ], column_name )
174
+ for column_name in columns_or_json ['cols' ]]
175
+ # fill in uids
176
+ for column in self :
177
+ column .id = columns_or_json ['cols' ][column .name ]['uid' ]
144
178
145
179
def __repr__ (self ):
146
180
return self ._columns .__repr__ ()
0 commit comments