def test_move_nested_trace_properties_existing_traces(self): fig = go.Figure( data=[ go.Bar(y=[1, 2, 3], marker={ 'opacity': 0.6, 'color': 'green' }), go.Scatter(x=[1, 3, 2], marker={ 'size': 30, 'color': [1, 1, 0] }), go.Bar(y=[3, 2, 1], marker={ 'opacity': 0.4, 'color': [1, 0.5, 0] }) ], layout={ 'barmode': 'group', 'template': { 'data': { 'bar': [go.Bar(marker={'line': { 'color': 'purple' }})] } } }) templated_fig = pio.to_templated(fig) expected_fig = go.Figure( data=[ go.Bar(y=[1, 2, 3]), go.Scatter(x=[1, 3, 2], marker={'color': [1, 1, 0]}), go.Bar(y=[3, 2, 1], marker={'color': [1, 0.5, 0]}) ], layout={ 'template': { 'data': { 'scatter': [go.Scatter(marker={'size': 30})], 'bar': [ go.Bar( marker={ 'opacity': 0.6, 'color': 'green', 'line': { 'color': 'purple' } }), go.Bar(marker={'opacity': 0.4}) ] }, 'layout': { 'barmode': 'group' } } }) self.assertEqual(pio.to_json(templated_fig), pio.to_json(expected_fig))
def test_move_nested_trace_properties(self): fig = go.Figure( data=[ go.Bar(y=[1, 2, 3], marker={"opacity": 0.6, "color": "green"}), go.Scatter(x=[1, 3, 2], marker={"size": 30, "color": [1, 1, 0]}), go.Bar(y=[3, 2, 1], marker={"opacity": 0.4, "color": [1, 0.5, 0]}), ], layout={"barmode": "group"}, ) templated_fig = pio.to_templated(fig) expected_fig = go.Figure( data=[ go.Bar(y=[1, 2, 3]), go.Scatter(x=[1, 3, 2], marker={"color": [1, 1, 0]}), go.Bar(y=[3, 2, 1], marker={"color": [1, 0.5, 0]}), ], layout={ "template": { "data": { "scatter": [go.Scatter(marker={"size": 30})], "bar": [ go.Bar(marker={"opacity": 0.6, "color": "green"}), go.Bar(marker={"opacity": 0.4}), ], }, "layout": {"barmode": "group"}, } }, ) self.assertEqual(pio.to_json(templated_fig), pio.to_json(expected_fig))
def test_from_json(fig1): fig1_json = json.dumps(fig1, **opts) fig1_loaded = pio.from_json(fig1_json) # Check return type assert isinstance(fig1_loaded, go.Figure) # Check return json assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict())
def test_from_json_output_type(fig1, fig_type_spec, fig_type): fig1_json = json.dumps(fig1, **opts) fig1_loaded = pio.from_json(fig1_json, output_type=fig_type_spec) # Check return type assert isinstance(fig1_loaded, fig_type) # Check return json assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict())
def test_deepcopy_figure(fig1): fig_copied = copy.deepcopy(fig1) # Contents should be equal assert pio.to_json(fig_copied) == pio.to_json(fig1) # Identities should be distinct assert fig_copied is not fig1 assert fig_copied.layout is not fig1.layout assert fig_copied.data is not fig1.data
def test_pickle_figure_subplots_round_trip(fig_subplots): fig_copied = pickle.loads(pickle.dumps(fig_subplots)) # Contents should be equal assert pio.to_json(fig_copied) == pio.to_json(fig_subplots) # Should be possible to add new trace to subplot location fig_subplots.add_bar(y=[0, 0, 1], row=1, col=2) fig_copied.add_bar(y=[0, 0, 1], row=1, col=2) # And contents should be still equal assert pio.to_json(fig_copied) == pio.to_json(fig_subplots)
def test_read_json_from_filelike(fig1, fig_type_spec, fig_type): # Configure file-like mock filemock = MagicMock() filemock.read.return_value = pio.to_json(fig1) # read_json on mock file fig1_loaded = pio.read_json(filemock, output_type=fig_type_spec) # Check return type assert isinstance(fig1_loaded, fig_type) # Check loaded figure assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict())
def getSources(): content = request.get_json() # [fig, labels, parsed_dict] thdict = { 'fig': pio.to_json(get_DAG()[0]), 'labels': get_DAG()[1], 'dictionary': get_DAG()[2] } response = app.response_class(response=pio.to_json(get_DAG()[0]), status=200, mimetype='application/json') return response
def test_move_nested_trace_properties_existing_traces(self): fig = go.Figure( data=[ go.Bar(y=[1, 2, 3], marker={'opacity': 0.6, 'color': 'green'}), go.Scatter(x=[1, 3, 2], marker={'size': 30, 'color': [1, 1, 0]}), go.Bar(y=[3, 2, 1], marker={'opacity': 0.4, 'color': [1, 0.5, 0]}) ], layout={'barmode': 'group', 'template': { 'data': { 'bar': [go.Bar(marker={ 'line': {'color': 'purple'}})] } }} ) templated_fig = pio.to_templated(fig) expected_fig = go.Figure( data=[ go.Bar(y=[1, 2, 3]), go.Scatter(x=[1, 3, 2], marker={'color': [1, 1, 0]}), go.Bar(y=[3, 2, 1], marker={'color': [1, 0.5, 0]}) ], layout={ 'template': { 'data': { 'scatter': [go.Scatter(marker={'size': 30})], 'bar': [ go.Bar(marker={'opacity': 0.6, 'color': 'green', 'line': { 'color': 'purple' }}), go.Bar(marker={'opacity': 0.4}) ]}, 'layout': { 'barmode': 'group' } } } ) self.assertEqual(pio.to_json(templated_fig), pio.to_json(expected_fig))
def test_from_json_skip_invalid(fig1): dict1 = fig1.to_dict() # Set bad property name dict1['data'][0]['marker']['bogus'] = 123 # Set property with bad value dict1['data'][0]['marker']['size'] = -1 # Serialize to json bad_json = json.dumps(dict1, **opts) fig1_loaded = pio.from_json(bad_json, skip_invalid=True) # Check loaded figure assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict())
def test_from_json_skip_invalid(fig1): dict1 = fig1.to_dict() # Set bad property name dict1["data"][0]["marker"]["bogus"] = 123 # Set property with bad value dict1["data"][0]["marker"]["size"] = -1 # Serialize to json bad_json = json.dumps(dict1, **opts) fig1_loaded = pio.from_json(bad_json, skip_invalid=True) # Check loaded figure assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict())
def test_read_json_from_file_string(fig1, fig_type_spec, fig_type): with tempfile.TemporaryDirectory() as dir_name: # Write json file path = os.path.join(dir_name, "fig1.json") with open(path, "w") as f: f.write(pio.to_json(fig1)) # read json from file as string fig1_loaded = pio.read_json(path, output_type=fig_type_spec) # Check return type assert isinstance(fig1_loaded, fig_type) # Check loaded figure assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict())
def test_to_json_remove_uids(fig1): dict1 = fig1.to_dict() for trace in dict1['data']: trace.pop('uid', None) assert pio.to_json(fig1) == json.dumps( dict1, **opts)
def test_read_json_from_file_string(fig1, fig_type_spec, fig_type): with tempfile.TemporaryDirectory() as dir_name: # Write json file path = os.path.join(dir_name, 'fig1.json') with open(path, 'w') as f: f.write(pio.to_json(fig1)) # read json from file as string fig1_loaded = pio.read_json(path, output_type=fig_type_spec) # Check return type assert isinstance(fig1_loaded, fig_type) # Check loaded figure assert pio.to_json(fig1_loaded) == pio.to_json(fig1.to_dict())
def test_mimetype_combination(fig1): pio.renderers.default = 'png+jupyterlab' # Configure renderer so that we can use the same parameters # to build expected image below pio.renderers['png'].width = 400 pio.renderers['png'].height = 500 pio.renderers['png'].scale = 1 # pdf image_bytes = pio.to_image( fig1, format='png', width=400, height=500, scale=1) image_str = base64.b64encode(image_bytes).decode('utf8') # plotly mimetype plotly_mimetype_dict = json.loads( pio.to_json(fig1, remove_uids=False)) plotly_mimetype_dict['config'] = { 'plotlyServerURL': get_config()['plotly_domain']} # Build expected bundle expected = { 'image/png': image_str, plotly_mimetype: plotly_mimetype_dict, } pio.renderers.render_on_display = False assert fig1._repr_mimebundle_(None, None) is None pio.renderers.render_on_display = True bundle = fig1._repr_mimebundle_(None, None) assert bundle == expected
def plot(self): x_reg = np.arange(min(self.xdata), max(self.xdata), (max(self.xdata) - min(self.xdata)) / 1000) y_reg = [] aux = 0.0 dgr = 0 for x in x_reg: for c in self.coefficients: aux += c * pow(x, dgr) dgr += 1 y_reg.append(aux) aux = 0.0 dgr = 0 fig = go.Figure() fig.add_trace( go.Scatter(x=self.xdata, y=self.ydata, fill=None, name='Dados originais', mode='markers')) fig.add_trace( go.Scatter(x=x_reg, y=y_reg, fill=None, name='Dados da regressão')) fig.update_layout(title="Regressão Polinomial", xaxis=dict(title="X"), yaxis=dict(title="Y")) self.json_data = pio.to_json(fig) diverter = StreamDiverter() fig.show(renderer='iframe') self.plot_address = diverter.srcExtractor()
def make_plotplotly(results_json: str, *args, **kwargs) -> str: import plotly.io as plotlyio results = Results.from_json(results_json) plot = Results.plotplotly(results, return_plotly_figure=True, **kwargs) plot_json = plotlyio.to_json(plot) return plot_json
def figure_to_data_package(self, fig, title, dec): self._dp.add_view( spec_type='plotly', name='', title=title, #'Fordeling av oppgaver basert på måned', description=dec, spec=plio.to_json(fig), resources='')
def test_json_renderer_show_override(fig1): pio.renderers.default = 'notebook' expected_bundle = {'application/json': json.loads( pio.to_json(fig1, remove_uids=False))} with mock.patch('IPython.display.display') as mock_display: pio.show(fig1, renderer='json') mock_display.assert_called_once_with(expected_bundle, raw=True)
def to_mimebundle(self, fig_dict): config = _get_jconfig(self.config) if config: fig_dict['config'] = config json_compatible_fig_dict = json.loads( to_json(fig_dict, validate=False, remove_uids=False)) return {'application/vnd.plotly.v1+json': json_compatible_fig_dict}
def to_mimebundle(self, fig_dict): config = _get_jconfig(self.config) if config: fig_dict["config"] = config json_compatible_fig_dict = json.loads( to_json(fig_dict, validate=False, remove_uids=False)) return {"application/vnd.plotly.v1+json": json_compatible_fig_dict}
def test_plotly_mimetype_renderer_show(fig1, renderer): pio.renderers.default = renderer expected = {plotly_mimetype: json.loads(pio.to_json(fig1, remove_uids=False))} expected[plotly_mimetype]["config"] = {"plotlyServerURL": "https://plot.ly"} with mock.patch("IPython.display.display") as mock_display: pio.show(fig1) mock_display.assert_called_once_with(expected, raw=True)
def test_write_json_filelike(fig1, pretty, remove_uids): # Configure file-like mock filemock = MagicMock() # write_json to mock file pio.write_json(fig1, filemock, pretty=pretty, remove_uids=remove_uids) # check write contents expected = pio.to_json(fig1, pretty=pretty, remove_uids=remove_uids) filemock.write.assert_called_once_with(expected)
def test_json_renderer_show(fig1): pio.renderers.default = "json" expected_bundle = { "application/json": json.loads(pio.to_json(fig1, remove_uids=False)) } with mock.patch("IPython.display.display") as mock_display: pio.show(fig1) mock_display.assert_called_once_with(expected_bundle, raw=True)
def plot(self): self.fig.update_layout(title="Estudo de Zonas de Fluxo", xaxis=dict(title="Phi-Z"), yaxis=dict(title="RQI"), xaxis_type='log', yaxis_type='log') self.fig.add_trace(go.Scatter(x=self.phi_z, y=self.rqi, fill=None, name='Dados', mode='markers')) self.json = pio.to_json(self.fig) diverter = StreamDiverter() self.fig.show(renderer='iframe') self.plot_path = diverter.srcExtractor()
def test_json_renderer_mimetype(fig1): pio.renderers.default = 'json' expected = {'application/json': json.loads( pio.to_json(fig1, remove_uids=False))} pio.renderers.render_on_display = False assert fig1._repr_mimebundle_(None, None) is None pio.renderers.render_on_display = True bundle = fig1._repr_mimebundle_(None, None) assert bundle == expected
def test_deepcopy_figure_subplots(fig_subplots): fig_copied = copy.deepcopy(fig_subplots) # Contents should be equal assert pio.to_json(fig_copied) == pio.to_json(fig_subplots) # Subplot metadata should be equal assert fig_subplots._grid_ref == fig_copied._grid_ref assert fig_subplots._grid_str == fig_copied._grid_str # Identities should be distinct assert fig_copied is not fig_subplots assert fig_copied.layout is not fig_subplots.layout assert fig_copied.data is not fig_subplots.data # Should be possible to add new trace to subplot location fig_subplots.add_bar(y=[0, 0, 1], row=1, col=2) fig_copied.add_bar(y=[0, 0, 1], row=1, col=2) # And contents should be still equal assert pio.to_json(fig_copied) == pio.to_json(fig_subplots)
def test_plotly_mimetype_renderer_show(fig1, renderer): pio.renderers.default = renderer expected = {plotly_mimetype: json.loads( pio.to_json(fig1, remove_uids=False))} expected[plotly_mimetype]['config'] = { 'plotlyServerURL': 'https://plot.ly'} with mock.patch('IPython.display.display') as mock_display: pio.show(fig1) mock_display.assert_called_once_with(expected, raw=True)
def test_plotly_mimetype_renderer_mimetype(fig1, renderer): pio.renderers.default = renderer expected = {plotly_mimetype: json.loads( pio.to_json(fig1, remove_uids=False))} expected[plotly_mimetype]['config'] = { 'plotlyServerURL': 'https://plot.ly'} pio.renderers.render_on_display = False assert fig1._repr_mimebundle_(None, None) is None pio.renderers.render_on_display = True bundle = fig1._repr_mimebundle_(None, None) assert bundle == expected
def test_write_json_from_file_string(fig1, pretty, remove_uids): with tempfile.TemporaryDirectory() as dir_name: # Write json path = os.path.join(dir_name, "fig1.json") pio.write_json(fig1, path, pretty=pretty, remove_uids=remove_uids) # Open as text file with open(path, "r") as f: result = f.read() # Check contents that were written expected = pio.to_json(fig1, pretty=pretty, remove_uids=remove_uids) assert result == expected
def test_write_json_from_file_string(fig1, pretty, remove_uids): with tempfile.TemporaryDirectory() as dir_name: # Write json path = os.path.join(dir_name, 'fig1.json') pio.write_json(fig1, path, pretty=pretty, remove_uids=remove_uids) # Open as text file with open(path, 'r') as f: result = f.read() # Check contents that were written expected = pio.to_json(fig1, pretty=pretty, remove_uids=remove_uids) assert result == expected
def test_json_renderer_mimetype(fig1): pio.renderers.default = "json" expected = {"application/json": json.loads(pio.to_json(fig1, remove_uids=False))} pio.renderers.render_on_display = False with mock.patch("IPython.display.display") as mock_display: fig1._ipython_display_() mock_display.assert_not_called() pio.renderers.render_on_display = True with mock.patch("IPython.display.display") as mock_display: fig1._ipython_display_() mock_display.assert_called_once_with(expected, raw=True)
def fig_to_json_html(fig, pconfig): if pconfig.get('auto_margin'): fig.update_layout(margin=dict(l=40, r=20, t=40, b=40)) if pconfig.get('ylab'): fig.update_layout(yaxis=dict(title_text=pconfig['ylab'])) if pconfig.get('xlab'): fig.update_layout(xaxis=dict(title_text=pconfig['xlab'])) if pconfig.get('title'): fig.update_layout(title_text=pconfig['title'], title_x=0.5) json_str = to_json(fig) html = '<script id="{id}" type="text/json">{json}</script>'.format( id=pconfig['data_id'], json=json_str) return html
def create_chart(self, data): """ Creates chart using example data. """ table = [ go.Table(header={ 'values': list(data.columns), 'fill': { 'color': self.table_header_color }, 'align': 'left' }, cells={ 'values': [data[c] for c in data.columns], 'align': ['right' for c in data.columns] }, columnwidth=[.1 for c in data.columns]) ] fig = dict(data=table) return plio.to_json(fig)
def _build_viz_figure(visualization): if visualization is None: _type = "none" figure = "null" elif isinstance(visualization, go.Figure): _type = "plotly" figure = json.loads(to_json(visualization)) elif isinstance(visualization, str): _type = "html" figure = _build_base64_frame_src(visualization) else: # NOTE: This error is largely specific to Dash components, # all Dash component visualizations are being replaced with D3 soon. _type = "html" msg = "This visualization is not yet supported in the cloud environment." log.debug("Visualization type cannot render: {}".format(type(visualization))) figure = _build_error_frame(msg) return {"type": _type, "figure": figure}
def api_tab(): """ Name: api_tab Objet: Permet le traitement de l'affichage du graphique pour les questions quantitatives. :return: Renvoi un JSON de la figure, afin de l'afficher dans la route '/tableau'. """ nom_formation = request.json["nom_formation"] conn = get_db() # Requête SQL pour récupérer la liste des questions quantitatives tab_score = pd.read_sql( """ SELECT session.id ,question.libelle as question, reponse.score as score from reponse inner join question on question.id = reponse.question_id inner join session on session.id = reponse.session_id where score is not null and session.id in (SELECT DISTINCT session.id FROM session inner join reponse on session.id = reponse.session_id where reponse.question_id = 14 AND reponse.choix_id= %s) ;""", conn, params=(nom_formation, )) # Pivote 'tab_score' pour avoir les questions en colonnes tab_score_pivot = pd.DataFrame.pivot(tab_score, index="id", columns="question", values="score") question_quant = request.json[ "question_quant"] # Récupère la question choisi dans '/tableau' fig = px.histogram(tab_score_pivot, x=question_quant, histnorm="percent", barmode='relative', nbins=8) figure = to_json(fig) return figure
def make_plotplotly(memory_id: str): # Ensure that a memory with this ID exists. if not delegate.job_complete(memory_id): return "Something broke", 404 # Grab the memorys. memory: Results = delegate.job_results(memory_id) # Plot the figure without rendering, returning the backing datastructure. memorys_plot = memory.plotplotly(return_plotly_figure=True) # Generate plot JSON, encode, and compress. plot_json = plotlyio.to_json(memorys_plot) compressed_plot = bz2.compress(plot_json.encode()) # Create and return the HTTP response. response = make_response(compressed_plot) response.headers["Content-Encoding"] = "bzip2" return response, 200
def test_to_json_pretty_print(fig1): assert pio.to_json(fig1, remove_uids=False, pretty=True) == json.dumps( fig1, **pretty_opts)
def test_to_json_validate(fig1): dict1 = fig1.to_dict() dict1['layout']['bogus'] = 37 with pytest.raises(ValueError): pio.to_json(dict1)
def test_pickle_figure_round_trip(fig1): fig_copied = pickle.loads(pickle.dumps(fig1)) # Contents should be equal assert pio.to_json(fig_copied) == pio.to_json(fig1)
def test_to_json(fig1): assert pio.to_json(fig1, remove_uids=False) == json.dumps( fig1, **opts)
def to_mimebundle(self, fig_dict): value = json.loads(to_json( fig_dict, validate=False, remove_uids=False)) return {'application/json': value}
def test_to_json_validate_false(fig1): dict1 = fig1.to_dict() dict1['layout']['bogus'] = 37 assert pio.to_json(dict1, validate=False) == json.dumps( dict1, **opts)