def init_notebook_mode(): """ Initialize Plotly Offline mode in an IPython Notebook. Run this function at the start of an IPython notebook to load the necessary javascript files for creating Plotly graphs with plotly.offline.iplot. """ if not tools._ipython_imported: raise ImportError('`iplot` can only run inside an IPython Notebook.') from IPython.display import HTML, display if not os.path.exists(PLOTLY_OFFLINE_BUNDLE): raise PlotlyError('Plotly Offline source file at {source_path} ' 'is not found.\n' 'If you have a Plotly Offline license, then try ' 'running plotly.offline.download_plotlyjs(url) ' 'with a licensed download url.\n' "Don't have a Plotly Offline license? " 'Contact [email protected] learn more about licensing.\n' 'Questions? [email protected].'.format( source_path=PLOTLY_OFFLINE_BUNDLE)) global __PLOTLY_OFFLINE_INITIALIZED __PLOTLY_OFFLINE_INITIALIZED = True display( HTML('<script type="text/javascript">' + open(PLOTLY_OFFLINE_BUNDLE).read() + '</script>'))
def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True): """ Draw plotly graphs inside an IPython notebook without connecting to an external server. To save the chart to Plotly Cloud or Plotly Enterprise, use `plotly.plotly.iplot`. To embed an image of the chart, use `plotly.image.ishow`. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) ``` """ if not __PLOTLY_OFFLINE_INITIALIZED: raise PlotlyError('\n'.join([ 'Plotly Offline mode has not been initialized in this notebook. ' 'Run: ', '', 'import plotly', 'plotly.offline.init_notebook_mode() ' '# run at the start of every ipython notebook', ])) if not tools._ipython_imported: raise ImportError('`iplot` can only run inside an IPython Notebook.') from IPython.display import HTML, display plot_html, plotdivid, width, height = _plot_html(figure_or_data, show_link, link_text, validate, '100%', 525, global_requirejs=True) display(HTML(plot_html))
class TestQtPlotlyExporter(): def setup_class(self): data = Data(x=[1, 2, 3], y=[2, 3, 4], label='data') dc = DataCollection([data]) self.app = GlueApplication(dc) data.style.color = '#000000' v = self.app.new_data_viewer(HistogramViewer, data=data) v.component = data.id['y'] v.xmin = 0 v.xmax = 10 v.bins = 20 self.args, self.kwargs = build_plotly_call(self.app) def teardown_class(self): self.app.close() self.app = None def get_exporter(self): return QtPlotlyExporter(plotly_args=self.args, plotly_kwargs=self.kwargs) def test_default_no_credentials(self, tmpdir): credentials_file = tmpdir.join('.credentials').strpath make_credentials_file(credentials_file) with patch('plotly.tools.CREDENTIALS_FILE', credentials_file): exporter = self.get_exporter() assert not exporter.radio_account_config.isChecked() assert exporter.radio_account_manual.isChecked() assert exporter.radio_sharing_secret.isChecked() def test_default_with_credentials(self, tmpdir): credentials_file = tmpdir.join('.credentials').strpath make_credentials_file(credentials_file, username='******', api_key='batmobile') with patch('plotly.tools.CREDENTIALS_FILE', credentials_file): exporter = self.get_exporter() assert exporter.radio_account_config.isChecked() assert 'username: batman' in exporter.radio_account_config.text() assert exporter.radio_sharing_secret.isChecked() def test_edit_username_toggle_custom(self, tmpdir): credentials_file = tmpdir.join('.credentials').strpath make_credentials_file(credentials_file, username='******', api_key='batmobile') with patch('plotly.tools.CREDENTIALS_FILE', credentials_file): exporter = self.get_exporter() assert exporter.radio_account_config.isChecked() exporter.username = '******' assert exporter.radio_account_manual.isChecked() exporter.radio_account_config.setChecked(True) assert exporter.radio_account_config.isChecked() exporter.api_key = 'a' assert exporter.radio_account_manual.isChecked() def test_accept_default(self, tmpdir): credentials_file = tmpdir.join('.credentials').strpath make_credentials_file(credentials_file, username='******', api_key='batmobile') with patch('plotly.tools.CREDENTIALS_FILE', credentials_file): with patch('plotly.plotly.plot', mock.MagicMock()): with patch('plotly.plotly.sign_in', mock.MagicMock()): with patch('webbrowser.open_new_tab') as open_new_tab: exporter = self.get_exporter() exporter.accept() assert exporter.text_status.text( ) == 'Exporting succeeded' ERRORS = [(PlotlyError(SIGN_IN_ERROR), 'Authentication failed'), (PlotlyError(MAX_PRIVATE_ERROR), 'Maximum number of private plots reached'), (PlotlyError('Oh noes!'), 'An unexpected error occurred'), (TypeError('A banana is not an apple'), 'An unexpected error occurred')] @pytest.mark.parametrize(('error', 'status'), ERRORS) def test_accept_errors(self, tmpdir, error, status): credentials_file = tmpdir.join('.credentials').strpath make_credentials_file(credentials_file, username='******', api_key='batmobile') plot = mock.MagicMock(side_effect=error) sign_in = mock.MagicMock() with patch('plotly.tools.CREDENTIALS_FILE', credentials_file): with patch('plotly.plotly.sign_in', sign_in): with patch('plotly.plotly.plot', plot): with patch('webbrowser.open_new_tab'): exporter = self.get_exporter() exporter.accept() assert exporter.text_status.text() == status def test_fix_url(self, tmpdir): credentials_file = tmpdir.join('.credentials').strpath make_credentials_file(credentials_file, username='******', api_key='batmobile') plot = mock.MagicMock( return_value= 'https://plot.ly/~batman/6?share_key=rbkWvJQn6cyj3HMMGROiqI') sign_in = mock.MagicMock() with patch('plotly.tools.CREDENTIALS_FILE', credentials_file): with patch('plotly.plotly.sign_in', sign_in): with patch('plotly.plotly.plot', plot): with patch('webbrowser.open_new_tab') as open_new_tab: exporter = self.get_exporter() exporter.accept() assert open_new_tab.called_once_with( 'https://plot.ly/~batman/6/?share_key=rbkWvJQn6cyj3HMMGROiqI' )
def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True, image=None, filename='plot_image', image_width=800, image_height=600): """ Draw plotly graphs inside an IPython notebook without connecting to an external server. To save the chart to Plotly Cloud or Plotly Enterprise, use `plotly.plotly.iplot`. To embed an image of the chart, use `plotly.image.ishow`. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets the format of the image to be downloaded, if we choose to download an image. This parameter has a default value of None indicating that no image should be downloaded. filename (default='plot') -- Sets the name of the file your image will be saved to. The extension should not be included. image_height (default=600) -- Specifies the height of the image in `px`. image_width (default=800) -- Specifies the width of the image in `px`. Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) # We can also download an image of the plot by setting the image to the format you want. e.g. `image='png'` iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png') ``` """ if not __PLOTLY_OFFLINE_INITIALIZED: raise PlotlyError('\n'.join([ 'Plotly Offline mode has not been initialized in this notebook. ' 'Run: ', '', 'import plotly', 'plotly.offline.init_notebook_mode() ' '# run at the start of every ipython notebook', ])) if not tools._ipython_imported: raise ImportError('`iplot` can only run inside an IPython Notebook.') plot_html, plotdivid, width, height = _plot_html(figure_or_data, show_link, link_text, validate, '100%', 525, global_requirejs=True) display(HTML(plot_html)) if image: if image not in __IMAGE_FORMATS: raise ValueError('The image parameter must be one of the following' ': {}'.format(__IMAGE_FORMATS)) # if image is given, and is a valid format, we will download the image script = get_image_download_script('iplot').format(format=image, width=image_width, height=image_height, filename=filename, plot_id=plotdivid) # allow time for the plot to draw time.sleep(1) # inject code to download an image of the plot display(HTML(script))
def create_choropleth(fips, values, scope=["usa"], binning_endpoints=None, colorscale=None, order=None, simplify_county=0.02, simplify_state=0.02, asp=None, show_hover=True, show_state_data=True, state_outline=None, county_outline=None, centroid_marker=None, round_legend_values=False, exponent_format=False, legend_title="", **layout_options): """ Returns figure for county choropleth. Uses data from package_data. :param (list) fips: list of FIPS values which correspond to the con catination of state and county ids. An example is '01001'. :param (list) values: list of numbers/strings which correspond to the fips list. These are the values that will determine how the counties are colored. :param (list) scope: list of states and/or states abbreviations. Fits all states in the camera tightly. Selecting ['usa'] is the equivalent of appending all 50 states into your scope list. Selecting only 'usa' does not include 'Alaska', 'Puerto Rico', 'American Samoa', 'Commonwealth of the Northern Mariana Islands', 'Guam', 'United States Virgin Islands'. These must be added manually to the list. Default = ['usa'] :param (list) binning_endpoints: ascending numbers which implicitly define real number intervals which are used as bins. The colorscale used must have the same number of colors as the number of bins and this will result in a categorical colormap. :param (list) colorscale: a list of colors with length equal to the number of categories of colors. The length must match either all unique numbers in the 'values' list or if endpoints is being used, the number of categories created by the endpoints.\n For example, if binning_endpoints = [4, 6, 8], then there are 4 bins: [-inf, 4), [4, 6), [6, 8), [8, inf) :param (list) order: a list of the unique categories (numbers/bins) in any desired order. This is helpful if you want to order string values to a chosen colorscale. :param (float) simplify_county: determines the simplification factor for the counties. The larger the number, the fewer vertices and edges each polygon has. See http://toblerity.org/shapely/manual.html#object.simplify for more information. Default = 0.02 :param (float) simplify_state: simplifies the state outline polygon. See http://toblerity.org/shapely/manual.html#object.simplify for more information. Default = 0.02 :param (float) asp: the width-to-height aspect ratio for the camera. Default = 2.5 :param (bool) show_hover: show county hover and centroid info :param (bool) show_state_data: reveals state boundary lines :param (dict) state_outline: dict of attributes of the state outline including width and color. See https://plot.ly/python/reference/#scatter-marker-line for all valid params :param (dict) county_outline: dict of attributes of the county outline including width and color. See https://plot.ly/python/reference/#scatter-marker-line for all valid params :param (dict) centroid_marker: dict of attributes of the centroid marker. The centroid markers are invisible by default and appear visible on selection. See https://plot.ly/python/reference/#scatter-marker for all valid params :param (bool) round_legend_values: automatically round the numbers that appear in the legend to the nearest integer. Default = False :param (bool) exponent_format: if set to True, puts numbers in the K, M, B number format. For example 4000.0 becomes 4.0K Default = False :param (str) legend_title: title that appears above the legend :param **layout_options: a **kwargs argument for all layout parameters Example 1: Florida ``` import plotly.plotly as py import plotly.figure_factory as ff import numpy as np import pandas as pd df_sample = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv' ) df_sample_r = df_sample[df_sample['STNAME'] == 'Florida'] values = df_sample_r['TOT_POP'].tolist() fips = df_sample_r['FIPS'].tolist() binning_endpoints = list(np.mgrid[min(values):max(values):4j]) colorscale = ["#030512","#1d1d3b","#323268","#3d4b94","#3e6ab0", "#4989bc","#60a7c7","#85c5d3","#b7e0e4","#eafcfd"] fig = ff.create_choropleth( fips=fips, values=values, scope=['Florida'], show_state_data=True, colorscale=colorscale, binning_endpoints=binning_endpoints, round_legend_values=True, plot_bgcolor='rgb(229,229,229)', paper_bgcolor='rgb(229,229,229)', legend_title='Florida Population', county_outline={'color': 'rgb(255,255,255)', 'width': 0.5}, exponent_format=True, ) py.iplot(fig, filename='choropleth_florida') ``` Example 2: New England ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd NE_states = ['Connecticut', 'Maine', 'Massachusetts', 'New Hampshire', 'Rhode Island'] df_sample = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv' ) df_sample_r = df_sample[df_sample['STNAME'].isin(NE_states)] colorscale = ['rgb(68.0, 1.0, 84.0)', 'rgb(66.0, 64.0, 134.0)', 'rgb(38.0, 130.0, 142.0)', 'rgb(63.0, 188.0, 115.0)', 'rgb(216.0, 226.0, 25.0)'] values = df_sample_r['TOT_POP'].tolist() fips = df_sample_r['FIPS'].tolist() fig = ff.create_choropleth( fips=fips, values=values, scope=NE_states, show_state_data=True ) py.iplot(fig, filename='choropleth_new_england') ``` Example 3: California and Surrounding States ``` import plotly.plotly as py import plotly.figure_factory as ff import pandas as pd df_sample = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv' ) df_sample_r = df_sample[df_sample['STNAME'] == 'California'] values = df_sample_r['TOT_POP'].tolist() fips = df_sample_r['FIPS'].tolist() colorscale = [ 'rgb(193, 193, 193)', 'rgb(239,239,239)', 'rgb(195, 196, 222)', 'rgb(144,148,194)', 'rgb(101,104,168)', 'rgb(65, 53, 132)' ] fig = ff.create_choropleth( fips=fips, values=values, colorscale=colorscale, scope=['CA', 'AZ', 'Nevada', 'Oregon', ' Idaho'], binning_endpoints=[14348, 63983, 134827, 426762, 2081313], county_outline={'color': 'rgb(255,255,255)', 'width': 0.5}, legend_title='California Counties', title='California and Nearby States' ) py.iplot(fig, filename='choropleth_california_and_surr_states_outlines') ``` Example 4: USA ``` import plotly.plotly as py import plotly.figure_factory as ff import numpy as np import pandas as pd df_sample = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/laucnty16.csv' ) df_sample['State FIPS Code'] = df_sample['State FIPS Code'].apply( lambda x: str(x).zfill(2) ) df_sample['County FIPS Code'] = df_sample['County FIPS Code'].apply( lambda x: str(x).zfill(3) ) df_sample['FIPS'] = ( df_sample['State FIPS Code'] + df_sample['County FIPS Code'] ) binning_endpoints = list(np.linspace(1, 12, len(colorscale) - 1)) colorscale = ["#f7fbff", "#ebf3fb", "#deebf7", "#d2e3f3", "#c6dbef", "#b3d2e9", "#9ecae1", "#85bcdb", "#6baed6", "#57a0ce", "#4292c6", "#3082be", "#2171b5", "#1361a9", "#08519c", "#0b4083","#08306b"] fips = df_sample['FIPS'] values = df_sample['Unemployment Rate (%)'] fig = ff.create_choropleth( fips=fips, values=values, scope=['usa'], binning_endpoints=binning_endpoints, colorscale=colorscale, show_hover=True, centroid_marker={'opacity': 0}, asp=2.9, title='USA by Unemployment %', legend_title='Unemployment %' ) py.iplot(fig, filename='choropleth_full_usa') ``` """ # ensure optional modules imported if not _plotly_geo: raise ValueError(""" The create_choropleth figure factory requires the plotly-geo package. Install using pip with: $ pip install plotly-geo Or, install using conda with $ conda install -c plotly plotly-geo """) if not gp or not shapefile or not shapely: raise ImportError( "geopandas, pyshp and shapely must be installed for this figure " "factory.\n\nRun the following commands to install the correct " "versions of the following modules:\n\n" "```\n" "$ pip install geopandas==0.3.0\n" "$ pip install pyshp==1.2.10\n" "$ pip install shapely==1.6.3\n" "```\n" "If you are using Windows, follow this post to properly " "install geopandas and dependencies:" "http://geoffboeing.com/2014/09/using-geopandas-windows/\n\n" "If you are using Anaconda, do not use PIP to install the " "packages above. Instead use conda to install them:\n\n" "```\n" "$ conda install plotly\n" "$ conda install geopandas\n" "```") df, df_state = _create_us_counties_df(st_to_state_name_dict, state_to_st_dict) fips_polygon_map = dict(zip(df["FIPS"].tolist(), df["geometry"].tolist())) if not state_outline: state_outline = {"color": "rgb(240, 240, 240)", "width": 1} if not county_outline: county_outline = {"color": "rgb(0, 0, 0)", "width": 0} if not centroid_marker: centroid_marker = {"size": 3, "color": "white", "opacity": 1} # ensure centroid markers appear on selection if "opacity" not in centroid_marker: centroid_marker.update({"opacity": 1}) if len(fips) != len(values): raise PlotlyError("fips and values must be the same length") # make fips, values into lists if isinstance(fips, pd.core.series.Series): fips = fips.tolist() if isinstance(values, pd.core.series.Series): values = values.tolist() # make fips numeric fips = map(lambda x: int(x), fips) if binning_endpoints: intervals = utils.endpts_to_intervals(binning_endpoints) LEVELS = _intervals_as_labels(intervals, round_legend_values, exponent_format) else: if not order: LEVELS = sorted(list(set(values))) else: # check if order is permutation # of unique color col values same_sets = sorted(list(set(values))) == set(order) no_duplicates = not any(order.count(x) > 1 for x in order) if same_sets and no_duplicates: LEVELS = order else: raise PlotlyError( "if you are using a custom order of unique values from " "your color column, you must: have all the unique values " "in your order and have no duplicate items") if not colorscale: colorscale = [] viridis_colors = clrs.colorscale_to_colors( clrs.PLOTLY_SCALES["Viridis"]) viridis_colors = clrs.color_parser(viridis_colors, clrs.hex_to_rgb) viridis_colors = clrs.color_parser(viridis_colors, clrs.label_rgb) viri_len = len(viridis_colors) + 1 viri_intervals = utils.endpts_to_intervals( list(np.linspace(0, 1, viri_len)))[1:-1] for L in np.linspace(0, 1, len(LEVELS)): for idx, inter in enumerate(viri_intervals): if L == 0: break elif inter[0] < L <= inter[1]: break intermed = (L - viri_intervals[idx][0]) / (viri_intervals[idx][1] - viri_intervals[idx][0]) float_color = clrs.find_intermediate_color(viridis_colors[idx], viridis_colors[idx], intermed, colortype="rgb") # make R,G,B into int values float_color = clrs.unlabel_rgb(float_color) float_color = clrs.unconvert_from_RGB_255(float_color) int_rgb = clrs.convert_to_RGB_255(float_color) int_rgb = clrs.label_rgb(int_rgb) colorscale.append(int_rgb) if len(colorscale) < len(LEVELS): raise PlotlyError( "You have {} LEVELS. Your number of colors in 'colorscale' must " "be at least the number of LEVELS: {}. If you are " "using 'binning_endpoints' then 'colorscale' must have at " "least len(binning_endpoints) + 2 colors".format( len(LEVELS), min(LEVELS, LEVELS[:20]))) color_lookup = dict(zip(LEVELS, colorscale)) x_traces = dict(zip(LEVELS, [[] for i in range(len(LEVELS))])) y_traces = dict(zip(LEVELS, [[] for i in range(len(LEVELS))])) # scope if isinstance(scope, str): raise PlotlyError("'scope' must be a list/tuple/sequence") scope_names = [] extra_states = [ "Alaska", "Commonwealth of the Northern Mariana Islands", "Puerto Rico", "Guam", "United States Virgin Islands", "American Samoa", ] for state in scope: if state.lower() == "usa": scope_names = df["STATE_NAME"].unique() scope_names = list(scope_names) for ex_st in extra_states: try: scope_names.remove(ex_st) except ValueError: pass else: if state in st_to_state_name_dict.keys(): state = st_to_state_name_dict[state] scope_names.append(state) df_state = df_state[df_state["STATE_NAME"].isin(scope_names)] plot_data = [] x_centroids = [] y_centroids = [] centroid_text = [] fips_not_in_shapefile = [] if not binning_endpoints: for index, f in enumerate(fips): level = values[index] try: fips_polygon_map[f].type ( x_traces, y_traces, x_centroids, y_centroids, centroid_text, ) = _calculations( df, fips, values, index, f, simplify_county, level, x_centroids, y_centroids, centroid_text, x_traces, y_traces, fips_polygon_map, ) except KeyError: fips_not_in_shapefile.append(f) else: for index, f in enumerate(fips): for j, inter in enumerate(intervals): if inter[0] < values[index] <= inter[1]: break level = LEVELS[j] try: fips_polygon_map[f].type ( x_traces, y_traces, x_centroids, y_centroids, centroid_text, ) = _calculations( df, fips, values, index, f, simplify_county, level, x_centroids, y_centroids, centroid_text, x_traces, y_traces, fips_polygon_map, ) except KeyError: fips_not_in_shapefile.append(f) if len(fips_not_in_shapefile) > 0: msg = ("Unrecognized FIPS Values\n\nWhoops! It looks like you are " "trying to pass at least one FIPS value that is not in " "our shapefile of FIPS and data for the counties. Your " "choropleth will still show up but these counties cannot " "be shown.\nUnrecognized FIPS are: {}".format( fips_not_in_shapefile)) warnings.warn(msg) x_states = [] y_states = [] for index, row in df_state.iterrows(): if df_state["geometry"][index].type == "Polygon": x = row.geometry.simplify(simplify_state).exterior.xy[0].tolist() y = row.geometry.simplify(simplify_state).exterior.xy[1].tolist() x_states = x_states + x y_states = y_states + y elif df_state["geometry"][index].type == "MultiPolygon": x = [ poly.simplify(simplify_state).exterior.xy[0].tolist() for poly in df_state["geometry"][index] ] y = [ poly.simplify(simplify_state).exterior.xy[1].tolist() for poly in df_state["geometry"][index] ] for segment in range(len(x)): x_states = x_states + x[segment] y_states = y_states + y[segment] x_states.append(np.nan) y_states.append(np.nan) x_states.append(np.nan) y_states.append(np.nan) for lev in LEVELS: county_data = dict( type="scatter", mode="lines", x=x_traces[lev], y=y_traces[lev], line=county_outline, fill="toself", fillcolor=color_lookup[lev], name=lev, hoverinfo="none", ) plot_data.append(county_data) if show_hover: hover_points = dict( type="scatter", showlegend=False, legendgroup="centroids", x=x_centroids, y=y_centroids, text=centroid_text, name="US Counties", mode="markers", marker={ "color": "white", "opacity": 0 }, hoverinfo="text", ) centroids_on_select = dict( selected=dict(marker=centroid_marker), unselected=dict(marker=dict(opacity=0)), ) hover_points.update(centroids_on_select) plot_data.append(hover_points) if show_state_data: state_data = dict( type="scatter", legendgroup="States", line=state_outline, x=x_states, y=y_states, hoverinfo="text", showlegend=False, mode="lines", ) plot_data.append(state_data) DEFAULT_LAYOUT = dict( hovermode="closest", xaxis=dict( autorange=False, range=USA_XRANGE, showgrid=False, zeroline=False, fixedrange=True, showticklabels=False, ), yaxis=dict( autorange=False, range=USA_YRANGE, showgrid=False, zeroline=False, fixedrange=True, showticklabels=False, ), margin=dict(t=40, b=20, r=20, l=20), width=900, height=450, dragmode="select", legend=dict(traceorder="reversed", xanchor="right", yanchor="top", x=1, y=1), annotations=[], ) fig = dict(data=plot_data, layout=DEFAULT_LAYOUT) fig["layout"].update(layout_options) fig["layout"]["annotations"].append( dict( x=1, y=1.05, xref="paper", yref="paper", xanchor="right", showarrow=False, text="<b>" + legend_title + "</b>", )) if len(scope) == 1 and scope[0].lower() == "usa": xaxis_range_low = -125.0 xaxis_range_high = -55.0 yaxis_range_low = 25.0 yaxis_range_high = 49.0 else: xaxis_range_low = float("inf") xaxis_range_high = float("-inf") yaxis_range_low = float("inf") yaxis_range_high = float("-inf") for trace in fig["data"]: if all(isinstance(n, Number) for n in trace["x"]): calc_x_min = min(trace["x"] or [float("inf")]) calc_x_max = max(trace["x"] or [float("-inf")]) if calc_x_min < xaxis_range_low: xaxis_range_low = calc_x_min if calc_x_max > xaxis_range_high: xaxis_range_high = calc_x_max if all(isinstance(n, Number) for n in trace["y"]): calc_y_min = min(trace["y"] or [float("inf")]) calc_y_max = max(trace["y"] or [float("-inf")]) if calc_y_min < yaxis_range_low: yaxis_range_low = calc_y_min if calc_y_max > yaxis_range_high: yaxis_range_high = calc_y_max # camera zoom fig["layout"]["xaxis"]["range"] = [xaxis_range_low, xaxis_range_high] fig["layout"]["yaxis"]["range"] = [yaxis_range_low, yaxis_range_high] # aspect ratio if asp is None: usa_x_range = USA_XRANGE[1] - USA_XRANGE[0] usa_y_range = USA_YRANGE[1] - USA_YRANGE[0] asp = usa_x_range / usa_y_range # based on your figure width = float(fig["layout"]["xaxis"]["range"][1] - fig["layout"]["xaxis"]["range"][0]) height = float(fig["layout"]["yaxis"]["range"][1] - fig["layout"]["yaxis"]["range"][0]) center = ( sum(fig["layout"]["xaxis"]["range"]) / 2.0, sum(fig["layout"]["yaxis"]["range"]) / 2.0, ) if height / width > (1 / asp): new_width = asp * height fig["layout"]["xaxis"]["range"][0] = center[0] - new_width * 0.5 fig["layout"]["xaxis"]["range"][1] = center[0] + new_width * 0.5 else: new_height = (1 / asp) * width fig["layout"]["yaxis"]["range"][0] = center[1] - new_height * 0.5 fig["layout"]["yaxis"]["range"][1] = center[1] + new_height * 0.5 return go.Figure(fig)
def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True, image=None, filename='plot_image', image_width=800, image_height=600, config=None): """ Draw plotly graphs inside an IPython or Jupyter notebook without connecting to an external server. To save the chart to Plotly Cloud or Plotly Enterprise, use `plotly.plotly.iplot`. To embed an image of the chart, use `plotly.image.ishow`. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. image (default=None |'png' |'jpeg' |'svg' |'webp') -- This parameter sets the format of the image to be downloaded, if we choose to download an image. This parameter has a default value of None indicating that no image should be downloaded. Please note: for higher resolution images and more export options, consider making requests to our image servers. Type: `help(py.image)` for more details. filename (default='plot') -- Sets the name of the file your image will be saved to. The extension should not be included. image_height (default=600) -- Specifies the height of the image in `px`. image_width (default=800) -- Specifies the width of the image in `px`. config (default=None) -- Plot view options dictionary. Keyword arguments `show_link` and `link_text` set the associated options in this dictionary if it doesn't contain them already. Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) # We can also download an image of the plot by setting the image to the format you want. e.g. `image='png'` iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}], image='png') ``` """ if not __PLOTLY_OFFLINE_INITIALIZED: raise PlotlyError('\n'.join([ 'Plotly Offline mode has not been initialized in this notebook. ' 'Run: ', '', 'import plotly', 'plotly.offline.init_notebook_mode() ' '# run at the start of every ipython notebook', ])) if not ipython: raise ImportError('`iplot` can only run inside an IPython Notebook.') config = dict(config) if config else {} config.setdefault('showLink', show_link) config.setdefault('linkText', link_text) plot_html, plotdivid, width, height = _plot_html( figure_or_data, config, validate, '100%', 525, True ) figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) # Though it can add quite a bit to the display-bundle size, we include # multiple representations of the plot so that the display environment can # choose which one to act on. data = _json.loads(_json.dumps(figure['data'], cls=plotly.utils.PlotlyJSONEncoder)) layout = _json.loads(_json.dumps(figure.get('layout', {}), cls=plotly.utils.PlotlyJSONEncoder)) frames = _json.loads(_json.dumps(figure.get('frames', None), cls=plotly.utils.PlotlyJSONEncoder)) fig = {'data': data, 'layout': layout} if frames: fig['frames'] = frames display_bundle = { 'application/vnd.plotly.v1+json': fig, 'text/html': plot_html, 'text/vnd.plotly.v1+html': plot_html } ipython_display.display(display_bundle, raw=True) if image: if image not in __IMAGE_FORMATS: raise ValueError('The image parameter must be one of the following' ': {}'.format(__IMAGE_FORMATS) ) # if image is given, and is a valid format, we will download the image script = get_image_download_script('iplot').format(format=image, width=image_width, height=image_height, filename=filename, plot_id=plotdivid) # allow time for the plot to draw time.sleep(1) # inject code to download an image of the plot ipython_display.display(ipython_display.HTML(script))
def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly', validate=True): """ Draw plotly graphs inside an IPython notebook without connecting to an external server. To save the chart to Plotly Cloud or Plotly Enterprise, use `plotly.plotly.iplot`. To embed an image of the chart, use `plotly.image.ishow`. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link validate (default=True) -- validate that all of the keys in the figure are valid? omit if your version of plotly.js has become outdated with your version of graph_reference.json or if you need to include extra, unnecessary keys in your figure. Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) ``` """ if not __PLOTLY_OFFLINE_INITIALIZED: raise PlotlyError('\n'.join([ 'Plotly Offline mode has not been initialized in this notebook. ' 'Run: ', '', 'import plotly', 'plotly.offline.init_notebook_mode() ' '# run at the start of every ipython notebook', ])) if not tools._ipython_imported: raise ImportError('`iplot` can only run inside an IPython Notebook.') from IPython.display import HTML, display figure = tools.return_figure_from_figure_or_data(figure_or_data, validate) width = figure.get('layout', {}).get('width', '100%') height = figure.get('layout', {}).get('height', 525) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' plotdivid = uuid.uuid4() jdata = json.dumps(figure.get('data', []), cls=utils.PlotlyJSONEncoder) jlayout = json.dumps(figure.get('layout', {}), cls=utils.PlotlyJSONEncoder) config = {} config['showLink'] = show_link config['linkText'] = link_text jconfig = json.dumps(config) # TODO: The get_config 'source of truth' should # really be somewhere other than plotly.plotly plotly_platform_url = plotly.plotly.get_config().get('plotly_domain', 'https://plot.ly') if (plotly_platform_url != 'https://plot.ly' and link_text == 'Export to plot.ly'): link_domain = plotly_platform_url\ .replace('https://', '')\ .replace('http://', '') link_text = link_text.replace('plot.ly', link_domain) display(HTML( '<script type="text/javascript">' 'window.PLOTLYENV=window.PLOTLYENV || {};' 'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";' '</script>' )) script = '\n'.join([ 'Plotly.plot("{id}", {data}, {layout}, {config}).then(function() {{', ' $(".{id}.loading").remove();', '}})' ]).format(id=plotdivid, data=jdata, layout=jlayout, config=jconfig) display(HTML('' '<div class="{id} loading" style="color: rgb(50,50,50);">' 'Drawing...</div>' '<div id="{id}" style="height: {height}; width: {width};" ' 'class="plotly-graph-div">' '</div>' '<script type="text/javascript">' '{script}' '</script>' ''.format(id=plotdivid, script=script, height=height, width=width)))
def iplot(figure_or_data, show_link=True, link_text='Export to plot.ly'): """ Draw plotly graphs inside an IPython notebook without connecting to an external server. To save the chart to Plotly Cloud or Plotly Enterprise, use `plotly.plotly.iplot`. To embed an image of the chart, use `plotly.image.ishow`. figure_or_data -- a plotly.graph_objs.Figure or plotly.graph_objs.Data or dict or list that describes a Plotly graph. See https://plot.ly/python/ for examples of graph descriptions. Keyword arguments: show_link (default=True) -- display a link in the bottom-right corner of of the chart that will export the chart to Plotly Cloud or Plotly Enterprise link_text (default='Export to plot.ly') -- the text of export link Example: ``` from plotly.offline import init_notebook_mode, iplot init_notebook_mode() iplot([{'x': [1, 2, 3], 'y': [5, 2, 7]}]) ``` """ if not __PLOTLY_OFFLINE_INITIALIZED: raise PlotlyError('\n'.join([ 'Plotly Offline mode has not been initialized in this notebook. ' 'Run: ', '', 'import plotly', 'plotly.offline.init_notebook_mode() ' '# run at the start of every ipython notebook', ])) if not tools._ipython_imported: raise ImportError('`iplot` can only run inside an IPython Notebook.') from IPython.display import HTML, display if isinstance(figure_or_data, dict): data = figure_or_data['data'] layout = figure_or_data.get('layout', {}) else: data = figure_or_data layout = {} width = layout.get('width', '100%') height = layout.get('height', 525) try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' try: float(width) except (ValueError, TypeError): pass else: width = str(width) + 'px' plotdivid = uuid.uuid4() jdata = json.dumps(data, cls=utils.PlotlyJSONEncoder) jlayout = json.dumps(layout, cls=utils.PlotlyJSONEncoder) if show_link is False: link_text = '' plotly_platform_url = session.get_session_config().get( 'plotly_domain', 'https://plot.ly') if (plotly_platform_url != 'https://plot.ly' and link_text == 'Export to plot.ly'): link_domain = plotly_platform_url\ .replace('https://', '')\ .replace('http://', '') link_text = link_text.replace('plot.ly', link_domain) display( HTML('<script type="text/javascript">' 'window.PLOTLYENV=window.PLOTLYENV || {};' 'window.PLOTLYENV.BASE_URL="' + plotly_platform_url + '";' 'Plotly.LINKTEXT = "' + link_text + '";' '</script>')) script = '\n'.join([ 'Plotly.plot("{id}", {data}, {layout}).then(function() {{', ' $(".{id}.loading").remove();', '}})' ]).format(id=plotdivid, data=jdata, layout=jlayout, link_text=link_text) display( HTML('' '<div class="{id} loading" style="color: rgb(50,50,50);">' 'Drawing...</div>' '<div id="{id}" style="height: {height}; width: {width};" ' 'class="plotly-graph-div">' '</div>' '<script type="text/javascript">' '{script}' '</script>' ''.format(id=plotdivid, script=script, height=height, width=width)))