diff --git a/packages/python/plotly/plotly/basedatatypes.py b/packages/python/plotly/plotly/basedatatypes.py index 5897b504002..077b5efc5e0 100644 --- a/packages/python/plotly/plotly/basedatatypes.py +++ b/packages/python/plotly/plotly/basedatatypes.py @@ -1593,16 +1593,19 @@ def add_trace(self, trace, row=None, col=None, secondary_y=None): Examples -------- + >>> from plotly import subplots >>> import plotly.graph_objs as go Add two Scatter traces to a figure + >>> fig = go.Figure() >>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2])) >>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2])) Add two Scatter traces to vertically stacked subplots + >>> fig = subplots.make_subplots(rows=2) >>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=1, col=1) >>> fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1) @@ -1665,15 +1668,18 @@ def add_traces(self, data, rows=None, cols=None, secondary_ys=None): Examples -------- + >>> from plotly import subplots >>> import plotly.graph_objs as go Add two Scatter traces to a figure + >>> fig = go.Figure() >>> fig.add_traces([go.Scatter(x=[1,2,3], y=[2,1,2]), ... go.Scatter(x=[1,2,3], y=[2,1,2])]) Add two Scatter traces to vertically stacked subplots + >>> fig = subplots.make_subplots(rows=2) >>> fig.add_traces([go.Scatter(x=[1,2,3], y=[2,1,2]), ... go.Scatter(x=[1,2,3], y=[2,1,2])], @@ -1773,10 +1779,12 @@ def append_trace(self, trace, row, col): Examples -------- + >>> from plotly import tools >>> import plotly.graph_objs as go - # stack two subplots vertically + >>> # stack two subplots vertically >>> fig = tools.make_subplots(rows=2) + This is the format of your plot grid: [ (1,1) x1,y1 ] [ (2,1) x2,y2 ] @@ -2425,6 +2433,7 @@ def batch_update(self): -------- For example, suppose we have a figure widget, `fig`, with a single trace. + >>> import plotly.graph_objs as go >>> fig = go.FigureWidget(data=[{'y': [3, 4, 2]}]) @@ -2593,6 +2602,7 @@ def batch_animate(self, duration=500, easing="cubic-in-out"): 2) Animate a change in the size and color of the trace's markers over 2 seconds using the elastic-in-out easing method + >>> with fig.batch_update(duration=2000, easing='elastic-in-out'): ... fig.data[0].marker.color = 'green' ... fig.data[0].marker.size = 20 @@ -3055,6 +3065,7 @@ def _parent_path_str(self): Examples -------- + >>> import plotly.graph_objs as go >>> go.Layout()._parent_path_str '' @@ -4582,6 +4593,7 @@ def on_hover(self, callback, append=False): Examples -------- + >>> from plotly.callbacks import Points, InputDeviceState >>> points, state = Points(), InputDeviceState() @@ -4641,6 +4653,7 @@ def on_unhover(self, callback, append=False): Examples -------- + >>> from plotly.callbacks import Points, InputDeviceState >>> points, state = Points(), InputDeviceState() @@ -4700,6 +4713,7 @@ def on_click(self, callback, append=False): Examples -------- + >>> from plotly.callbacks import Points, InputDeviceState >>> points, state = Points(), InputDeviceState() @@ -4758,6 +4772,7 @@ def on_selection(self, callback, append=False): Examples -------- + >>> from plotly.callbacks import Points >>> points = Points() @@ -4823,6 +4838,7 @@ def on_deselect(self, callback, append=False): Examples -------- + >>> from plotly.callbacks import Points >>> points = Points() diff --git a/packages/python/plotly/plotly/express/_doc.py b/packages/python/plotly/plotly/express/_doc.py index 39a133ef225..950a3953be7 100644 --- a/packages/python/plotly/plotly/express/_doc.py +++ b/packages/python/plotly/plotly/express/_doc.py @@ -27,13 +27,13 @@ colref_type, colref_desc, "Values from this column or array_like are used to position marks along the x axis in cartesian coordinates.", - "For horizontal `histogram`s, these values are used as inputs to `histfunc`.", + "For horizontal histograms, these values are used as inputs to `histfunc`.", ], y=[ colref_type, colref_desc, "Values from this column or array_like are used to position marks along the y axis in cartesian coordinates.", - "For vertical `histogram`s, these values are used as inputs to `histfunc`.", + "For vertical histograms, these values are used as inputs to `histfunc`.", ], z=[ colref_type, @@ -455,6 +455,7 @@ def make_docstring(fn): if param in docs else "(documentation missing from map)" ) + param_type = docs[param][0] result += "%s: %s\n%s\n" % (param, param_type, param_desc) result += "\nReturns\n-------\n" diff --git a/packages/python/plotly/plotly/figure_factory/_2d_density.py b/packages/python/plotly/plotly/figure_factory/_2d_density.py index 59c5559a8c8..5a96d4b3718 100644 --- a/packages/python/plotly/plotly/figure_factory/_2d_density.py +++ b/packages/python/plotly/plotly/figure_factory/_2d_density.py @@ -51,49 +51,47 @@ def create_2d_density( :param (float) height: the height of the chart :param (float) width: the width of the chart + Examples + -------- + Example 1: Simple 2D Density Plot - ``` - import plotly.plotly as py - from plotly.figure_factory create_2d_density - import numpy as np + >>> from plotly.figure_factory create_2d_density + + >>> import numpy as np - # Make data points - t = np.linspace(-1,1.2,2000) - x = (t**3)+(0.3*np.random.randn(2000)) - y = (t**6)+(0.3*np.random.randn(2000)) + >>> # Make data points + >>> t = np.linspace(-1,1.2,2000) + >>> x = (t**3)+(0.3*np.random.randn(2000)) + >>> y = (t**6)+(0.3*np.random.randn(2000)) - # Create a figure - fig = create_2D_density(x, y) + >>> # Create a figure + >>> fig = create_2D_density(x, y) - # Plot the data - py.iplot(fig, filename='simple-2d-density') - ``` + >>> # Plot the data + >>> fig.show() Example 2: Using Parameters - ``` - import plotly.plotly as py - from plotly.figure_factory create_2d_density - import numpy as np + >>> from plotly.figure_factory create_2d_density + + >>> import numpy as np - # Make data points - t = np.linspace(-1,1.2,2000) - x = (t**3)+(0.3*np.random.randn(2000)) - y = (t**6)+(0.3*np.random.randn(2000)) + >>> # Make data points + >>> t = np.linspace(-1,1.2,2000) + >>> x = (t**3)+(0.3*np.random.randn(2000)) + >>> y = (t**6)+(0.3*np.random.randn(2000)) - # Create custom colorscale - colorscale = ['#7A4579', '#D56073', 'rgb(236,158,105)', - (1, 1, 0.2), (0.98,0.98,0.98)] + >>> # Create custom colorscale + >>> colorscale = ['#7A4579', '#D56073', 'rgb(236,158,105)', + ... (1, 1, 0.2), (0.98,0.98,0.98)] - # Create a figure - fig = create_2D_density( - x, y, colorscale=colorscale, - hist_color='rgb(255, 237, 222)', point_size=3) + >>> # Create a figure + >>> fig = create_2D_density(x, y, colorscale=colorscale, + ... hist_color='rgb(255, 237, 222)', point_size=3) - # Plot the data - py.iplot(fig, filename='use-parameters') - ``` + >>> # Plot the data + >>> fig.show() """ # validate x and y are filled with numbers only diff --git a/packages/python/plotly/plotly/figure_factory/_annotated_heatmap.py b/packages/python/plotly/plotly/figure_factory/_annotated_heatmap.py index ec61aac8af8..c3b1e2fa989 100644 --- a/packages/python/plotly/plotly/figure_factory/_annotated_heatmap.py +++ b/packages/python/plotly/plotly/figure_factory/_annotated_heatmap.py @@ -84,17 +84,16 @@ def create_annotated_heatmap( call help(plotly.graph_objs.Heatmap) Example 1: Simple annotated heatmap with default configuration - ``` - import plotly.plotly as py - import plotly.figure_factory as FF - z = [[0.300000, 0.00000, 0.65, 0.300000], - [1, 0.100005, 0.45, 0.4300], - [0.300000, 0.00000, 0.65, 0.300000], - [1, 0.100005, 0.45, 0.00000]] + >>> import plotly.figure_factory as ff + + >>> z = [[0.300000, 0.00000, 0.65, 0.300000], + ... [1, 0.100005, 0.45, 0.4300], + ... [0.300000, 0.00000, 0.65, 0.300000], + ... [1, 0.100005, 0.45, 0.00000]] - figure = FF.create_annotated_heatmap(z) - py.iplot(figure) + >>> fig = ff.create_annotated_heatmap(z) + >>> fig.show() ``` """ diff --git a/packages/python/plotly/plotly/figure_factory/_bullet.py b/packages/python/plotly/plotly/figure_factory/_bullet.py index 5daaa823f60..111e713a3a4 100644 --- a/packages/python/plotly/plotly/figure_factory/_bullet.py +++ b/packages/python/plotly/plotly/figure_factory/_bullet.py @@ -238,49 +238,40 @@ def create_bullet( for more information on valid params. Example 1: Use a Dictionary - ``` - import plotly - import plotly.plotly as py - import plotly.figure_factory as ff - - data = [ - {"label": "Revenue", "sublabel": "US$, in thousands", - "range": [150, 225, 300], "performance": [220,270], "point": [250]}, - {"label": "Profit", "sublabel": "%", "range": [20, 25, 30], - "performance": [21, 23], "point": [26]}, - {"label": "Order Size", "sublabel":"US$, average","range": [350, 500, 600], - "performance": [100,320],"point": [550]}, - {"label": "New Customers", "sublabel": "count", "range": [1400, 2000, 2500], - "performance": [1000, 1650],"point": [2100]}, - {"label": "Satisfaction", "sublabel": "out of 5","range": [3.5, 4.25, 5], - "performance": [3.2, 4.7], "point": [4.4]} - ] - - fig = ff.create_bullet( - data, titles='label', subtitles='sublabel', markers='point', - measures='performance', ranges='range', orientation='h', - title='my simple bullet chart' - ) - py.iplot(fig) - ``` + + >>> import plotly.figure_factory as ff + + >>> data = [ + ... {"label": "revenue", "sublabel": "us$, in thousands", + ... "range": [150, 225, 300], "performance": [220,270], "point": [250]}, + ... {"label": "Profit", "sublabel": "%", "range": [20, 25, 30], + ... "performance": [21, 23], "point": [26]}, + ... {"label": "Order Size", "sublabel":"US$, average","range": [350, 500, 600], + ... "performance": [100,320],"point": [550]}, + ... {"label": "New Customers", "sublabel": "count", "range": [1400, 2000, 2500], + ... "performance": [1000, 1650],"point": [2100]}, + ... {"label": "Satisfaction", "sublabel": "out of 5","range": [3.5, 4.25, 5], + ... "performance": [3.2, 4.7], "point": [4.4]} + ... ] + + >>> fig = ff.create_bullet( + ... data, titles='label', subtitles='sublabel', markers='point', + ... measures='performance', ranges='range', orientation='h', + ... title='my simple bullet chart' + ... ) + >>> fig.show() Example 2: Use a DataFrame with Custom Colors - ``` - import plotly.plotly as py - import plotly.figure_factory as ff - - import pandas as pd - data = pd.read_json('https://cdn.rawgit.com/plotly/datasets/master/BulletData.json') + >>> import plotly.figure_factory as ff + >>> import pandas as pd + >>> data = pd.read_json('https://cdn.rawgit.com/plotly/datasets/master/BulletData.json') - fig = ff.create_bullet( - data, titles='title', markers='markers', measures='measures', - orientation='v', measure_colors=['rgb(14, 52, 75)', 'rgb(31, 141, 127)'], - scatter_options={'marker': {'symbol': 'circle'}}, width=700 - - ) - py.iplot(fig) - ``` + >>> fig = ff.create_bullet( + ... data, titles='title', markers='markers', measures='measures', + ... orientation='v', measure_colors=['rgb(14, 52, 75)', 'rgb(31, 141, 127)'], + ... scatter_options={'marker': {'symbol': 'circle'}}, width=700) + >>> fig.show() """ # validate df if not pd: diff --git a/packages/python/plotly/plotly/figure_factory/_candlestick.py b/packages/python/plotly/plotly/figure_factory/_candlestick.py index b012a60a596..db4cc507355 100644 --- a/packages/python/plotly/plotly/figure_factory/_candlestick.py +++ b/packages/python/plotly/plotly/figure_factory/_candlestick.py @@ -122,23 +122,21 @@ def create_candlestick(open, high, low, close, dates=None, direction="both", **k :rtype (dict): returns a representation of candlestick chart figure. Example 1: Simple candlestick chart from a Pandas DataFrame - ``` - import plotly.plotly as py - from plotly.figure_factory import create_candlestick - from datetime import datetime - import pandas.io.data as web + >>> from plotly.figure_factory import create_candlestick + >>> from datetime import datetime - df = web.DataReader("aapl", 'yahoo', datetime(2007, 10, 1), datetime(2009, 4, 1)) - fig = create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index) - py.plot(fig, filename='finance/aapl-candlestick', validate=False) - ``` + >>> import pandas.io.data as web + + >>> df = web.DataReader("aapl", 'yahoo', datetime(2007, 10, 1), datetime(2009, 4, 1)) + >>> fig = create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index) + >>> fig.show() Example 2: Add text and annotations to the candlestick chart - ``` - fig = create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index) - # Update the fig - all options here: https://plot.ly/python/reference/#Layout - fig['layout'].update({ + + >>> fig = create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index) + >>> # Update the fig - all options here: https://plot.ly/python/reference/#Layout + >>> fig['layout'].update({ 'title': 'The Great Recession', 'yaxis': {'title': 'AAPL Stock'}, 'shapes': [{ @@ -152,65 +150,59 @@ def create_candlestick(open, high, low, close, dates=None, direction="both", **k 'text': 'Official start of the recession' }] }) - py.plot(fig, filename='finance/aapl-recession-candlestick', validate=False) - ``` + >>> fig.show() Example 3: Customize the candlestick colors - ``` - import plotly.plotly as py - from plotly.figure_factory import create_candlestick - from plotly.graph_objs import Line, Marker - from datetime import datetime - - import pandas.io.data as web + + >>> from plotly.figure_factory import create_candlestick + >>> from plotly.graph_objs import Line, Marker + >>> from datetime import datetime - df = web.DataReader("aapl", 'yahoo', datetime(2008, 1, 1), datetime(2009, 4, 1)) + >>> import pandas.io.data as web - # Make increasing candlesticks and customize their color and name - fig_increasing = create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index, - direction='increasing', name='AAPL', - marker=Marker(color='rgb(150, 200, 250)'), - line=Line(color='rgb(150, 200, 250)')) + >>> df = web.DataReader("aapl", 'yahoo', datetime(2008, 1, 1), datetime(2009, 4, 1)) - # Make decreasing candlesticks and customize their color and name - fig_decreasing = create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index, - direction='decreasing', - marker=Marker(color='rgb(128, 128, 128)'), - line=Line(color='rgb(128, 128, 128)')) + >>> # Make increasing candlesticks and customize their color and name + >>> fig_increasing = create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index, + ... direction='increasing', name='AAPL', + ... marker=Marker(color='rgb(150, 200, 250)'), + ... line=Line(color='rgb(150, 200, 250)')) - # Initialize the figure - fig = fig_increasing + >>> # Make decreasing candlesticks and customize their color and name + >>> fig_decreasing = create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index, + ... direction='decreasing', + ... marker=Marker(color='rgb(128, 128, 128)'), + ... line=Line(color='rgb(128, 128, 128)')) - # Add decreasing data with .extend() - fig['data'].extend(fig_decreasing['data']) + >>> # Initialize the figure + >>> fig = fig_increasing - py.iplot(fig, filename='finance/aapl-candlestick-custom', validate=False) - ``` + >>> # Add decreasing data with .extend() + >>> fig['data'].extend(fig_decreasing['data']) + >>> fig.show() Example 4: Candlestick chart with datetime objects - ``` - import plotly.plotly as py - from plotly.figure_factory import create_candlestick - - from datetime import datetime - - # Add data - open_data = [33.0, 33.3, 33.5, 33.0, 34.1] - high_data = [33.1, 33.3, 33.6, 33.2, 34.8] - low_data = [32.7, 32.7, 32.8, 32.6, 32.8] - close_data = [33.0, 32.9, 33.3, 33.1, 33.1] - dates = [datetime(year=2013, month=10, day=10), - datetime(year=2013, month=11, day=10), - datetime(year=2013, month=12, day=10), - datetime(year=2014, month=1, day=10), - datetime(year=2014, month=2, day=10)] - - # Create ohlc - fig = create_candlestick(open_data, high_data, - low_data, close_data, dates=dates) - - py.iplot(fig, filename='finance/simple-candlestick', validate=False) - ``` + + >>> from plotly.figure_factory import create_candlestick + + >>> from datetime import datetime + + >>> # Add data + >>> open_data = [33.0, 33.3, 33.5, 33.0, 34.1] + >>> high_data = [33.1, 33.3, 33.6, 33.2, 34.8] + >>> low_data = [32.7, 32.7, 32.8, 32.6, 32.8] + >>> close_data = [33.0, 32.9, 33.3, 33.1, 33.1] + >>> dates = [datetime(year=2013, month=10, day=10), + ... datetime(year=2013, month=11, day=10), + ... datetime(year=2013, month=12, day=10), + ... datetime(year=2014, month=1, day=10), + ... datetime(year=2014, month=2, day=10)] + + >>> # Create ohlc + >>> fig = create_candlestick(open_data, high_data, + ... low_data, close_data, dates=dates) + >>> fig.show() + """ if dates is not None: utils.validate_equal_length(open, high, low, close, dates) diff --git a/packages/python/plotly/plotly/figure_factory/_county_choropleth.py b/packages/python/plotly/plotly/figure_factory/_county_choropleth.py index 5e8dfea47a0..eb0d6b45111 100644 --- a/packages/python/plotly/plotly/figure_factory/_county_choropleth.py +++ b/packages/python/plotly/plotly/figure_factory/_county_choropleth.py @@ -478,35 +478,33 @@ def create_choropleth( :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'] + Example 1: Florida:: + + import plotly.plotly as py + import plotly.figure_factory as ff - values = df_sample_r['TOT_POP'].tolist() - fips = df_sample_r['FIPS'].tolist() + import numpy as np + import pandas as pd - 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') - ``` + 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, + ) Example 2: New England ``` diff --git a/packages/python/plotly/plotly/figure_factory/_dendrogram.py b/packages/python/plotly/plotly/figure_factory/_dendrogram.py index 8ce371261f9..14ae27bccce 100644 --- a/packages/python/plotly/plotly/figure_factory/_dendrogram.py +++ b/packages/python/plotly/plotly/figure_factory/_dendrogram.py @@ -40,46 +40,38 @@ def create_dendrogram( :param (double) color_threshold: Value at which the separation of clusters will be made Example 1: Simple bottom oriented dendrogram - ``` - import plotly.plotly as py - from plotly.figure_factory import create_dendrogram - import numpy as np + >>> from plotly.figure_factory import create_dendrogram - X = np.random.rand(10,10) - dendro = create_dendrogram(X) - plot_url = py.plot(dendro, filename='simple-dendrogram') + >>> import numpy as np - ``` + >>> X = np.random.rand(10,10) + >>> fig = create_dendrogram(X) + >>> fig.show() Example 2: Dendrogram to put on the left of the heatmap - ``` - import plotly.plotly as py - from plotly.figure_factory import create_dendrogram + + >>> from plotly.figure_factory import create_dendrogram - import numpy as np + >>> import numpy as np - X = np.random.rand(5,5) - names = ['Jack', 'Oxana', 'John', 'Chelsea', 'Mark'] - dendro = create_dendrogram(X, orientation='right', labels=names) - dendro['layout'].update({'width':700, 'height':500}) - - py.iplot(dendro, filename='vertical-dendrogram') - ``` + >>> X = np.random.rand(5,5) + >>> names = ['Jack', 'Oxana', 'John', 'Chelsea', 'Mark'] + >>> dendro = create_dendrogram(X, orientation='right', labels=names) + >>> dendro['layout'].update({'width':700, 'height':500}) + >>> dendro.show() Example 3: Dendrogram with Pandas - ``` - import plotly.plotly as py - from plotly.figure_factory import create_dendrogram - - import numpy as np - import pandas as pd - - Index= ['A','B','C','D','E','F','G','H','I','J'] - df = pd.DataFrame(abs(np.random.randn(10, 10)), index=Index) - fig = create_dendrogram(df, labels=Index) - url = py.plot(fig, filename='pandas-dendrogram') - ``` + + >>> from plotly.figure_factory import create_dendrogram + + >>> import numpy as np + >>> import pandas as pd + + >>> Index= ['A','B','C','D','E','F','G','H','I','J'] + >>> df = pd.DataFrame(abs(np.random.randn(10, 10)), index=Index) + >>> fig = create_dendrogram(df, labels=Index) + >>> fig.show() """ if not scp or not scs or not sch: raise ImportError( diff --git a/packages/python/plotly/plotly/figure_factory/_distplot.py b/packages/python/plotly/plotly/figure_factory/_distplot.py index dd7d3adb1d9..2808931abe9 100644 --- a/packages/python/plotly/plotly/figure_factory/_distplot.py +++ b/packages/python/plotly/plotly/figure_factory/_distplot.py @@ -85,96 +85,83 @@ def create_distplot( :return (dict): Representation of a distplot figure. Example 1: Simple distplot of 1 data set - ``` - import plotly.plotly as py - from plotly.figure_factory import create_distplot - hist_data = [[1.1, 1.1, 2.5, 3.0, 3.5, - 3.5, 4.1, 4.4, 4.5, 4.5, - 5.0, 5.0, 5.2, 5.5, 5.5, - 5.5, 5.5, 5.5, 6.1, 7.0]] + >>> from plotly.figure_factory import create_distplot - group_labels = ['distplot example'] + >>> hist_data = [[1.1, 1.1, 2.5, 3.0, 3.5, + ... 3.5, 4.1, 4.4, 4.5, 4.5, + ... 5.0, 5.0, 5.2, 5.5, 5.5, + ... 5.5, 5.5, 5.5, 6.1, 7.0]] + >>> group_labels = ['distplot example'] + >>> fig = create_distplot(hist_data, group_labels) + >>> fig.show() - fig = create_distplot(hist_data, group_labels) - - url = py.plot(fig, filename='Simple distplot', validate=False) - ``` Example 2: Two data sets and added rug text - ``` - import plotly.plotly as py - from plotly.figure_factory import create_distplot - - # Add histogram data - hist1_x = [0.8, 1.2, 0.2, 0.6, 1.6, - -0.9, -0.07, 1.95, 0.9, -0.2, - -0.5, 0.3, 0.4, -0.37, 0.6] - hist2_x = [0.8, 1.5, 1.5, 0.6, 0.59, - 1.0, 0.8, 1.7, 0.5, 0.8, - -0.3, 1.2, 0.56, 0.3, 2.2] + + >>> from plotly.figure_factory import create_distplot + >>> # Add histogram data + >>> hist1_x = [0.8, 1.2, 0.2, 0.6, 1.6, + ... -0.9, -0.07, 1.95, 0.9, -0.2, + ... -0.5, 0.3, 0.4, -0.37, 0.6] + >>> hist2_x = [0.8, 1.5, 1.5, 0.6, 0.59, + ... 1.0, 0.8, 1.7, 0.5, 0.8, + ... -0.3, 1.2, 0.56, 0.3, 2.2] - # Group data together - hist_data = [hist1_x, hist2_x] + >>> # Group data together + >>> hist_data = [hist1_x, hist2_x] - group_labels = ['2012', '2013'] + >>> group_labels = ['2012', '2013'] - # Add text - rug_text_1 = ['a1', 'b1', 'c1', 'd1', 'e1', - 'f1', 'g1', 'h1', 'i1', 'j1', - 'k1', 'l1', 'm1', 'n1', 'o1'] + >>> # Add text + >>> rug_text_1 = ['a1', 'b1', 'c1', 'd1', 'e1', + ... 'f1', 'g1', 'h1', 'i1', 'j1', + ... 'k1', 'l1', 'm1', 'n1', 'o1'] - rug_text_2 = ['a2', 'b2', 'c2', 'd2', 'e2', - 'f2', 'g2', 'h2', 'i2', 'j2', - 'k2', 'l2', 'm2', 'n2', 'o2'] + >>> rug_text_2 = ['a2', 'b2', 'c2', 'd2', 'e2', + ... 'f2', 'g2', 'h2', 'i2', 'j2', + ... 'k2', 'l2', 'm2', 'n2', 'o2'] - # Group text together - rug_text_all = [rug_text_1, rug_text_2] + >>> # Group text together + >>> rug_text_all = [rug_text_1, rug_text_2] - # Create distplot - fig = create_distplot( - hist_data, group_labels, rug_text=rug_text_all, bin_size=.2) + >>> # Create distplot + >>> fig = create_distplot( + ... hist_data, group_labels, rug_text=rug_text_all, bin_size=.2) - # Add title - fig['layout'].update(title='Dist Plot') + >>> # Add title + >>> fig['layout'].update(title='Dist Plot') + >>> fig.show() - # Plot! - url = py.plot(fig, filename='Distplot with rug text', validate=False) - ``` Example 3: Plot with normal curve and hide rug plot - ``` - import plotly.plotly as py - from plotly.figure_factory import create_distplot - import numpy as np + + >>> from plotly.figure_factory import create_distplot + >>> import numpy as np - x1 = np.random.randn(190) - x2 = np.random.randn(200)+1 - x3 = np.random.randn(200)-1 - x4 = np.random.randn(210)+2 + >>> x1 = np.random.randn(190) + >>> x2 = np.random.randn(200)+1 + >>> x3 = np.random.randn(200)-1 + >>> x4 = np.random.randn(210)+2 - hist_data = [x1, x2, x3, x4] - group_labels = ['2012', '2013', '2014', '2015'] + >>> hist_data = [x1, x2, x3, x4] + >>> group_labels = ['2012', '2013', '2014', '2015'] - fig = create_distplot( - hist_data, group_labels, curve_type='normal', - show_rug=False, bin_size=.4) + >>> fig = create_distplot( + ... hist_data, group_labels, curve_type='normal', + ... show_rug=False, bin_size=.4) - url = py.plot(fig, filename='hist and normal curve', validate=False) Example 4: Distplot with Pandas - ``` - import plotly.plotly as py - from plotly.figure_factory import create_distplot - import numpy as np - import pandas as pd - - df = pd.DataFrame({'2012': np.random.randn(200), - '2013': np.random.randn(200)+1}) - py.iplot(create_distplot([df[c] for c in df.columns], df.columns), - filename='examples/distplot with pandas', - validate=False) - ``` + + >>> from plotly.figure_factory import create_distplot + >>> import numpy as np + >>> import pandas as pd + + >>> df = pd.DataFrame({'2012': np.random.randn(200), + >>> '2013': np.random.randn(200)+1}) + >>> fig = create_distplot([df[c] for c in df.columns], df.columns) + >>> fig.show() """ if colors is None: colors = [] diff --git a/packages/python/plotly/plotly/figure_factory/_facet_grid.py b/packages/python/plotly/plotly/figure_factory/_facet_grid.py index cc129468b1a..95e0f70edec 100644 --- a/packages/python/plotly/plotly/figure_factory/_facet_grid.py +++ b/packages/python/plotly/plotly/figure_factory/_facet_grid.py @@ -720,121 +720,94 @@ def create_facet_grid( :param (dict) kwargs: a dictionary of scatterplot arguments. Examples 1: One Way Faceting - ``` - import plotly.plotly as py - import plotly.figure_factory as ff - import pandas as pd + >>> import plotly.figure_factory as ff + >>> import pandas as pd + >>> mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt') - mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt') - - fig = ff.create_facet_grid( - mpg, - x='displ', - y='cty', - facet_col='cyl', - ) - py.iplot(fig, filename='facet_grid_mpg_one_way_facet') - ``` + >>> fig = ff.create_facet_grid( + ... mpg, + ... x='displ', + ... y='cty', + ... facet_col='cyl', + ... ) + >>> fig.show() Example 2: Two Way Faceting - ``` - import plotly.plotly as py - import plotly.figure_factory as ff - import pandas as pd + >>> import plotly.figure_factory as ff - mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt') + >>> import pandas as pd - fig = ff.create_facet_grid( - mpg, - x='displ', - y='cty', - facet_row='drv', - facet_col='cyl', - ) - py.iplot(fig, filename='facet_grid_mpg_two_way_facet') - ``` - - Example 3: Categorical Coloring - ``` - import plotly.plotly as py - import plotly.figure_factory as ff + >>> mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt') - import pandas as pd + >>> fig = ff.create_facet_grid( + ... mpg, + ... x='displ', + ... y='cty', + ... facet_row='drv', + ... facet_col='cyl', + ... ) + >>> fig.show() - mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt') + Example 3: Categorical Coloring - fig = ff.create_facet_grid( - mtcars, - x='mpg', - y='wt', - facet_col='cyl', - color_name='cyl', - color_is_cat=True, - ) - py.iplot(fig, filename='facet_grid_mpg_default_colors') - ``` + >>> import plotly.figure_factory as ff + >>> import pandas as pd + >>> mpg = pd.read_table('https://raw.githubusercontent.com/plotly/datasets/master/mpg_2017.txt') + >>> fig = ff.create_facet_grid( + ... mtcars, + ... x='mpg', + ... y='wt', + ... facet_col='cyl', + ... color_name='cyl', + ... color_is_cat=True, + ... ) + >>> fig.show() Example 4: Sequential Coloring - ``` - import plotly.plotly as py - import plotly.figure_factory as ff - - import pandas as pd - - tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv') - - fig = ff.create_facet_grid( - tips, - x='total_bill', - y='tip', - facet_row='sex', - facet_col='smoker', - color_name='size', - colormap='Viridis', - ) - py.iplot(fig, filename='facet_grid_tips_sequential_colors') - ``` - Example 5: Custom labels - ``` - import plotly.plotly as py - import plotly.figure_factory as ff + >>> import plotly.figure_factory as ff + >>> import pandas as pd + >>> tips = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/tips.csv') + + >>> fig = ff.create_facet_grid( + >>> tips, + ... x='total_bill', + ... y='tip', + ... facet_row='sex', + ... facet_col='smoker', + ... color_name='size', + ... colormap='Viridis', + ... ) + >>> fig.show() - import pandas as pd - - mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv') - - fig = ff.create_facet_grid( - mtcars, - x='wt', - y='mpg', - facet_col='cyl', - facet_col_labels={4: "$\\alpha$", 6: '$\\beta$', 8: '$\sqrt[y]{x}$'}, - ) + Example 5: Custom labels - py.iplot(fig, filename='facet_grid_mtcars_custom_labels') - ``` + >>> import plotly.figure_factory as ff + >>> import pandas as pd + >>> mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv') + >>> fig = ff.create_facet_grid( + ... mtcars, + ... x='wt', + ... y='mpg', + ... facet_col='cyl', + ... facet_col_labels={4: "$\\alpha$", 6: '$\\beta$', 8: '$\sqrt[y]{x}$'}, + ... ) + >>> fig.show() Example 6: Other Trace Type - ``` - import plotly.plotly as py - import plotly.figure_factory as ff - - import pandas as pd - - mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv') - - fig = ff.create_facet_grid( - mtcars, - x='wt', - facet_col='cyl', - trace_type='histogram', - ) - py.iplot(fig, filename='facet_grid_mtcars_other_trace_type') - ``` + >>> import plotly.figure_factory as ff + >>> import pandas as pd + >>> mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv') + >>> fig = ff.create_facet_grid( + ... mtcars, + ... x='wt', + ... facet_col='cyl', + ... trace_type='histogram', + ... ) + >>> fig.show() """ if not pd: raise ImportError("'pandas' must be installed for this figure_factory.") diff --git a/packages/python/plotly/plotly/figure_factory/_gantt.py b/packages/python/plotly/plotly/figure_factory/_gantt.py index 8af7a435381..f4ec5f58281 100644 --- a/packages/python/plotly/plotly/figure_factory/_gantt.py +++ b/packages/python/plotly/plotly/figure_factory/_gantt.py @@ -850,113 +850,95 @@ def create_gantt( :param (float) width: the width of the chart Example 1: Simple Gantt Chart - ``` - import plotly.plotly as py - from plotly.figure_factory import create_gantt - # Make data for chart - df = [dict(Task="Job A", Start='2009-01-01', Finish='2009-02-30'), - dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15'), - dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30')] + >>> from plotly.figure_factory import create_gantt - # Create a figure - fig = create_gantt(df) + >>> # Make data for chart + >>> df = [dict(Task="Job A", Start='2009-01-01', Finish='2009-02-30'), + ... dict(Task="Job B", Start='2009-03-05', Finish='2009-04-15'), + ... dict(Task="Job C", Start='2009-02-20', Finish='2009-05-30')] + + >>> # Create a figure + >>> fig = create_gantt(df) + >>> fig.show() - # Plot the data - py.iplot(fig, filename='Simple Gantt Chart', world_readable=True) - ``` Example 2: Index by Column with Numerical Entries - ``` - import plotly.plotly as py - from plotly.figure_factory import create_gantt - - # Make data for chart - df = [dict(Task="Job A", Start='2009-01-01', - Finish='2009-02-30', Complete=10), - dict(Task="Job B", Start='2009-03-05', - Finish='2009-04-15', Complete=60), - dict(Task="Job C", Start='2009-02-20', - Finish='2009-05-30', Complete=95)] - - # Create a figure with Plotly colorscale - fig = create_gantt(df, colors='Blues', index_col='Complete', - show_colorbar=True, bar_width=0.5, - showgrid_x=True, showgrid_y=True) - - # Plot the data - py.iplot(fig, filename='Numerical Entries', world_readable=True) - ``` + + >>> from plotly.figure_factory import create_gantt + + >>> # Make data for chart + >>> df = [dict(Task="Job A", Start='2009-01-01', + ... Finish='2009-02-30', Complete=10), + ... dict(Task="Job B", Start='2009-03-05', + ... Finish='2009-04-15', Complete=60), + ... dict(Task="Job C", Start='2009-02-20', + ... Finish='2009-05-30', Complete=95)] + + >>> # Create a figure with Plotly colorscale + >>> fig = create_gantt(df, colors='Blues', index_col='Complete', + ... show_colorbar=True, bar_width=0.5, + ... showgrid_x=True, showgrid_y=True) + >>> fig.show() + Example 3: Index by Column with String Entries - ``` - import plotly.plotly as py - from plotly.figure_factory import create_gantt - - # Make data for chart - df = [dict(Task="Job A", Start='2009-01-01', - Finish='2009-02-30', Resource='Apple'), - dict(Task="Job B", Start='2009-03-05', - Finish='2009-04-15', Resource='Grape'), - dict(Task="Job C", Start='2009-02-20', - Finish='2009-05-30', Resource='Banana')] - - # Create a figure with Plotly colorscale - fig = create_gantt(df, colors=['rgb(200, 50, 25)', (1, 0, 1), '#6c4774'], - index_col='Resource', reverse_colors=True, - show_colorbar=True) - - # Plot the data - py.iplot(fig, filename='String Entries', world_readable=True) - ``` + + >>> from plotly.figure_factory import create_gantt + + >>> # Make data for chart + >>> df = [dict(Task="Job A", Start='2009-01-01', + ... Finish='2009-02-30', Resource='Apple'), + ... dict(Task="Job B", Start='2009-03-05', + ... Finish='2009-04-15', Resource='Grape'), + ... dict(Task="Job C", Start='2009-02-20', + ... Finish='2009-05-30', Resource='Banana')] + + >>> # Create a figure with Plotly colorscale + >>> fig = create_gantt(df, colors=['rgb(200, 50, 25)', (1, 0, 1), '#6c4774'], + ... index_col='Resource', reverse_colors=True, + ... show_colorbar=True) + >>> fig.show() + Example 4: Use a dictionary for colors - ``` - import plotly.plotly as py - from plotly.figure_factory import create_gantt - - # Make data for chart - df = [dict(Task="Job A", Start='2009-01-01', - Finish='2009-02-30', Resource='Apple'), - dict(Task="Job B", Start='2009-03-05', - Finish='2009-04-15', Resource='Grape'), - dict(Task="Job C", Start='2009-02-20', - Finish='2009-05-30', Resource='Banana')] - - # Make a dictionary of colors - colors = {'Apple': 'rgb(255, 0, 0)', - 'Grape': 'rgb(170, 14, 200)', - 'Banana': (1, 1, 0.2)} - - # Create a figure with Plotly colorscale - fig = create_gantt(df, colors=colors, index_col='Resource', - show_colorbar=True) - - # Plot the data - py.iplot(fig, filename='dictioanry colors', world_readable=True) - ``` + + >>> from plotly.figure_factory import create_gantt + >>> # Make data for chart + >>> df = [dict(Task="Job A", Start='2009-01-01', + ... Finish='2009-02-30', Resource='Apple'), + ... dict(Task="Job B", Start='2009-03-05', + ... Finish='2009-04-15', Resource='Grape'), + ... dict(Task="Job C", Start='2009-02-20', + ... Finish='2009-05-30', Resource='Banana')] + + >>> # Make a dictionary of colors + >>> colors = {'Apple': 'rgb(255, 0, 0)', + ... 'Grape': 'rgb(170, 14, 200)', + ... 'Banana': (1, 1, 0.2)} + + >>> # Create a figure with Plotly colorscale + >>> fig = create_gantt(df, colors=colors, index_col='Resource', + ... show_colorbar=True) + + >>> fig.show() Example 5: Use a pandas dataframe - ``` - import plotly.plotly as py - from plotly.figure_factory import create_gantt - - import pandas as pd - - # Make data as a dataframe - df = pd.DataFrame([['Run', '2010-01-01', '2011-02-02', 10], - ['Fast', '2011-01-01', '2012-06-05', 55], - ['Eat', '2012-01-05', '2013-07-05', 94]], - columns=['Task', 'Start', 'Finish', 'Complete']) - - # Create a figure with Plotly colorscale - fig = create_gantt(df, colors='Blues', index_col='Complete', - show_colorbar=True, bar_width=0.5, - showgrid_x=True, showgrid_y=True) - - # Plot the data - py.iplot(fig, filename='data with dataframe', world_readable=True) - ``` + + >>> from plotly.figure_factory import create_gantt + >>> import pandas as pd + + >>> # Make data as a dataframe + >>> df = pd.DataFrame([['Run', '2010-01-01', '2011-02-02', 10], + ... ['Fast', '2011-01-01', '2012-06-05', 55], + ... ['Eat', '2012-01-05', '2013-07-05', 94]], + ... columns=['Task', 'Start', 'Finish', 'Complete']) + + >>> # Create a figure with Plotly colorscale + >>> fig = create_gantt(df, colors='Blues', index_col='Complete', + ... show_colorbar=True, bar_width=0.5, + ... showgrid_x=True, showgrid_y=True) + >>> fig.show() """ # validate gantt input data chart = validate_gantt(df) diff --git a/packages/python/plotly/plotly/figure_factory/_ohlc.py b/packages/python/plotly/plotly/figure_factory/_ohlc.py index 131d3df2d88..3122bb0a6c5 100644 --- a/packages/python/plotly/plotly/figure_factory/_ohlc.py +++ b/packages/python/plotly/plotly/figure_factory/_ohlc.py @@ -157,107 +157,96 @@ def create_ohlc(open, high, low, close, dates=None, direction="both", **kwargs): :rtype (dict): returns a representation of an ohlc chart figure. Example 1: Simple OHLC chart from a Pandas DataFrame - ``` - import plotly.plotly as py - from plotly.figure_factory import create_ohlc - from datetime import datetime - import pandas.io.data as web + >>> from plotly.figure_factory import create_ohlc + >>> from datetime import datetime - df = web.DataReader("aapl", 'yahoo', datetime(2008, 8, 15), - datetime(2008, 10, 15)) - fig = create_ohlc(df.Open, df.High, df.Low, df.Close, dates=df.index) + >>> import pandas.io.data as web - py.plot(fig, filename='finance/aapl-ohlc') - ``` + >>> df = web.DataReader("aapl", 'yahoo', datetime(2008, 8, 15), + ... datetime(2008, 10, 15)) + >>> fig = create_ohlc(df.Open, df.High, df.Low, df.Close, dates=df.index) + >>> fig.show() Example 2: Add text and annotations to the OHLC chart - ``` - import plotly.plotly as py - from plotly.figure_factory import create_ohlc - from datetime import datetime - - import pandas.io.data as web - - df = web.DataReader("aapl", 'yahoo', datetime(2008, 8, 15), - datetime(2008, 10, 15)) - fig = create_ohlc(df.Open, df.High, df.Low, df.Close, dates=df.index) - - # Update the fig - options here: https://plot.ly/python/reference/#Layout - fig['layout'].update({ - 'title': 'The Great Recession', - 'yaxis': {'title': 'AAPL Stock'}, - 'shapes': [{ - 'x0': '2008-09-15', 'x1': '2008-09-15', 'type': 'line', - 'y0': 0, 'y1': 1, 'xref': 'x', 'yref': 'paper', - 'line': {'color': 'rgb(40,40,40)', 'width': 0.5} - }], - 'annotations': [{ - 'text': "the fall of Lehman Brothers", - 'x': '2008-09-15', 'y': 1.02, - 'xref': 'x', 'yref': 'paper', - 'showarrow': False, 'xanchor': 'left' - }] - }) - - py.plot(fig, filename='finance/aapl-recession-ohlc', validate=False) - ``` + + >>> from plotly.figure_factory import create_ohlc + >>> from datetime import datetime + + >>> import pandas.io.data as web + + >>> df = web.datareader("aapl", 'yahoo', datetime(2008, 8, 15), + ... datetime(2008, 10, 15)) + >>> fig = create_ohlc(df.open, df.high, df.low, df.close, dates=df.index) + + >>> # update the fig - options here: https://plot.ly/python/reference/#layout + >>> fig['layout'].update({ + ... 'title': 'the great recession', + ... 'yaxis': {'title': 'aapl stock'}, + ... 'shapes': [{ + ... 'x0': '2008-09-15', 'x1': '2008-09-15', 'type': 'line', + ... 'y0': 0, 'y1': 1, 'xref': 'x', 'yref': 'paper', + ... 'line': {'color': 'rgb(40,40,40)', 'width': 0.5} + ... }], + ... 'annotations': [{ + ... 'text': "the fall of lehman brothers", + ... 'x': '2008-09-15', 'y': 1.02, + ... 'xref': 'x', 'yref': 'paper', + ... 'showarrow': false, 'xanchor': 'left' + ... }] + ... }) + >>> fig.show() Example 3: Customize the OHLC colors - ``` - import plotly.plotly as py - from plotly.figure_factory import create_ohlc - from plotly.graph_objs import Line, Marker - from datetime import datetime - import pandas.io.data as web + >>> from plotly.figure_factory import create_ohlc + >>> from plotly.graph_objs import Line, Marker + >>> from datetime import datetime + + >>> import pandas.io.data as web - df = web.DataReader("aapl", 'yahoo', datetime(2008, 1, 1), - datetime(2009, 4, 1)) + >>> df = web.DataReader("aapl", 'yahoo', datetime(2008, 1, 1), + ... datetime(2009, 4, 1)) - # Make increasing ohlc sticks and customize their color and name - fig_increasing = create_ohlc(df.Open, df.High, df.Low, df.Close, - dates=df.index, direction='increasing', - name='AAPL', - line=Line(color='rgb(150, 200, 250)')) + >>> # Make increasing ohlc sticks and customize their color and name + >>> fig_increasing = create_ohlc(df.Open, df.High, df.Low, df.Close, + ... dates=df.index, direction='increasing', + ... name='AAPL', + ... line=Line(color='rgb(150, 200, 250)')) - # Make decreasing ohlc sticks and customize their color and name - fig_decreasing = create_ohlc(df.Open, df.High, df.Low, df.Close, - dates=df.index, direction='decreasing', - line=Line(color='rgb(128, 128, 128)')) + >>> # Make decreasing ohlc sticks and customize their color and name + >>> fig_decreasing = create_ohlc(df.Open, df.High, df.Low, df.Close, + ... dates=df.index, direction='decreasing', + ... line=Line(color='rgb(128, 128, 128)')) - # Initialize the figure - fig = fig_increasing + >>> # Initialize the figure + >>> fig = fig_increasing - # Add decreasing data with .extend() - fig['data'].extend(fig_decreasing['data']) + >>> # Add decreasing data with .extend() + >>> fig['data'].extend(fig_decreasing['data']) + >>> fig.show() - py.iplot(fig, filename='finance/aapl-ohlc-colors', validate=False) - ``` Example 4: OHLC chart with datetime objects - ``` - import plotly.plotly as py - from plotly.figure_factory import create_ohlc - - from datetime import datetime - - # Add data - open_data = [33.0, 33.3, 33.5, 33.0, 34.1] - high_data = [33.1, 33.3, 33.6, 33.2, 34.8] - low_data = [32.7, 32.7, 32.8, 32.6, 32.8] - close_data = [33.0, 32.9, 33.3, 33.1, 33.1] - dates = [datetime(year=2013, month=10, day=10), - datetime(year=2013, month=11, day=10), - datetime(year=2013, month=12, day=10), - datetime(year=2014, month=1, day=10), - datetime(year=2014, month=2, day=10)] - - # Create ohlc - fig = create_ohlc(open_data, high_data, low_data, close_data, dates=dates) - - py.iplot(fig, filename='finance/simple-ohlc', validate=False) - ``` + + >>> from plotly.figure_factory import create_ohlc + + >>> from datetime import datetime + + >>> # Add data + >>> open_data = [33.0, 33.3, 33.5, 33.0, 34.1] + >>> high_data = [33.1, 33.3, 33.6, 33.2, 34.8] + >>> low_data = [32.7, 32.7, 32.8, 32.6, 32.8] + >>> close_data = [33.0, 32.9, 33.3, 33.1, 33.1] + >>> dates = [datetime(year=2013, month=10, day=10), + ... datetime(year=2013, month=11, day=10), + ... datetime(year=2013, month=12, day=10), + ... datetime(year=2014, month=1, day=10), + ... datetime(year=2014, month=2, day=10)] + + >>> # Create ohlc + >>> fig = create_ohlc(open_data, high_data, low_data, close_data, dates=dates) + >>> fig.show() """ if dates is not None: utils.validate_equal_length(open, high, low, close, dates) diff --git a/packages/python/plotly/plotly/figure_factory/_quiver.py b/packages/python/plotly/plotly/figure_factory/_quiver.py index e64f7eebfcb..e9503515ea1 100644 --- a/packages/python/plotly/plotly/figure_factory/_quiver.py +++ b/packages/python/plotly/plotly/figure_factory/_quiver.py @@ -32,84 +32,70 @@ def create_quiver( :rtype (dict): returns a representation of quiver figure. Example 1: Trivial Quiver - ``` - import plotly.plotly as py - from plotly.figure_factory import create_quiver - import math + >>> from plotly.figure_factory import create_quiver + >>> import math - # 1 Arrow from (0,0) to (1,1) - fig = create_quiver(x=[0], y=[0], u=[1], v=[1], scale=1) + >>> # 1 Arrow from (0,0) to (1,1) + >>> fig = create_quiver(x=[0], y=[0], u=[1], v=[1], scale=1) + >>> fig.show() - py.plot(fig, filename='quiver') - ``` Example 2: Quiver plot using meshgrid - ``` - import plotly.plotly as py - from plotly.figure_factory import create_quiver - import numpy as np - import math + >>> from plotly.figure_factory import create_quiver - # Add data - x,y = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2)) - u = np.cos(x)*y - v = np.sin(x)*y + >>> import numpy as np + >>> import math - #Create quiver - fig = create_quiver(x, y, u, v) + >>> # Add data + >>> x,y = np.meshgrid(np.arange(0, 2, .2), np.arange(0, 2, .2)) + >>> u = np.cos(x)*y + >>> v = np.sin(x)*y + + >>> #Create quiver + >>> fig = create_quiver(x, y, u, v) + >>> fig.show() - # Plot - py.plot(fig, filename='quiver') - ``` Example 3: Styling the quiver plot - ``` - import plotly.plotly as py - from plotly.figure_factory import create_quiver - import numpy as np - import math - # Add data - x, y = np.meshgrid(np.arange(-np.pi, math.pi, .5), - np.arange(-math.pi, math.pi, .5)) - u = np.cos(x)*y - v = np.sin(x)*y + >>> from plotly.figure_factory import create_quiver + >>> import numpy as np + >>> import math + + >>> # Add data + >>> x, y = np.meshgrid(np.arange(-np.pi, math.pi, .5), + ... np.arange(-math.pi, math.pi, .5)) + >>> u = np.cos(x)*y + >>> v = np.sin(x)*y - # Create quiver - fig = create_quiver(x, y, u, v, scale=.2, arrow_scale=.3, angle=math.pi/6, - name='Wind Velocity', line=dict(width=1)) + >>> # Create quiver + >>> fig = create_quiver(x, y, u, v, scale=.2, arrow_scale=.3, angle=math.pi/6, + ... name='Wind Velocity', line=dict(width=1)) - # Add title to layout - fig['layout'].update(title='Quiver Plot') + >>> # Add title to layout + >>> fig['layout'].update(title='Quiver Plot') + >>> fig.show() - # Plot - py.plot(fig, filename='quiver') - ``` Example 4: Forcing a fix scale ratio to maintain the arrow length - ``` - import plotly.plotly as py - from plotly.figure_factory import create_quiver - - import numpy as np - - # Add data - x,y = np.meshgrid(np.arange(0.5, 3.5, .5), np.arange(0.5, 4.5, .5)) - u = x - v = y - angle = np.arctan(v / u) - norm = 0.25 - u = norm * np.cos(angle) - v = norm * np.sin(angle) - - # Create quiver with a fix scale ratio - fig = create_quiver(x, y, u, v, scale = 1, scaleratio = 0.5) - - # Plot - py.plot(fig, filename='quiver') - ``` + + >>> from plotly.figure_factory import create_quiver + >>> import numpy as np + + >>> # Add data + >>> x,y = np.meshgrid(np.arange(0.5, 3.5, .5), np.arange(0.5, 4.5, .5)) + >>> u = x + >>> v = y + >>> angle = np.arctan(v / u) + >>> norm = 0.25 + >>> u = norm * np.cos(angle) + >>> v = norm * np.sin(angle) + + >>> # Create quiver with a fix scale ratio + >>> fig = create_quiver(x, y, u, v, scale = 1, scaleratio = 0.5) + >>> fig.show() """ utils.validate_equal_length(x, y, u, v) utils.validate_positive_scalars(arrow_scale=arrow_scale, scale=scale) diff --git a/packages/python/plotly/plotly/figure_factory/_scatterplot.py b/packages/python/plotly/plotly/figure_factory/_scatterplot.py index f7975d77dbf..9d606c1d7ac 100644 --- a/packages/python/plotly/plotly/figure_factory/_scatterplot.py +++ b/packages/python/plotly/plotly/figure_factory/_scatterplot.py @@ -892,161 +892,142 @@ def create_scatterplotmatrix( 'colorscale' in 'marker' Example 1: Vanilla Scatterplot Matrix - ``` - import plotly.plotly as py - from plotly.graph_objs import graph_objs - from plotly.figure_factory import create_scatterplotmatrix - import numpy as np - import pandas as pd + >>> from plotly.graph_objs import graph_objs + >>> from plotly.figure_factory import create_scatterplotmatrix - # Create dataframe - df = pd.DataFrame(np.random.randn(10, 2), - columns=['Column 1', 'Column 2']) + >>> import numpy as np + >>> import pandas as pd - # Create scatterplot matrix - fig = create_scatterplotmatrix(df) + >>> # Create dataframe + >>> df = pd.DataFrame(np.random.randn(10, 2), + ... columns=['Column 1', 'Column 2']) + + >>> # Create scatterplot matrix + >>> fig = create_scatterplotmatrix(df) + >>> fig.show() - # Plot - py.iplot(fig, filename='Vanilla Scatterplot Matrix') - ``` Example 2: Indexing a Column - ``` - import plotly.plotly as py - from plotly.graph_objs import graph_objs - from plotly.figure_factory import create_scatterplotmatrix - import numpy as np - import pandas as pd + >>> from plotly.graph_objs import graph_objs + >>> from plotly.figure_factory import create_scatterplotmatrix + + >>> import numpy as np + >>> import pandas as pd - # Create dataframe with index - df = pd.DataFrame(np.random.randn(10, 2), - columns=['A', 'B']) + >>> # Create dataframe with index + >>> df = pd.DataFrame(np.random.randn(10, 2), + ... columns=['A', 'B']) - # Add another column of strings to the dataframe - df['Fruit'] = pd.Series(['apple', 'apple', 'grape', 'apple', 'apple', - 'grape', 'pear', 'pear', 'apple', 'pear']) + >>> # Add another column of strings to the dataframe + >>> df['Fruit'] = pd.Series(['apple', 'apple', 'grape', 'apple', 'apple', + ... 'grape', 'pear', 'pear', 'apple', 'pear']) - # Create scatterplot matrix - fig = create_scatterplotmatrix(df, index='Fruit', size=10) + >>> # Create scatterplot matrix + >>> fig = create_scatterplotmatrix(df, index='Fruit', size=10) + >>> fig.show() - # Plot - py.iplot(fig, filename = 'Scatterplot Matrix with Index') - ``` Example 3: Styling the Diagonal Subplots - ``` - import plotly.plotly as py - from plotly.graph_objs import graph_objs - from plotly.figure_factory import create_scatterplotmatrix - import numpy as np - import pandas as pd + >>> from plotly.graph_objs import graph_objs + >>> from plotly.figure_factory import create_scatterplotmatrix + + >>> import numpy as np + >>> import pandas as pd - # Create dataframe with index - df = pd.DataFrame(np.random.randn(10, 4), - columns=['A', 'B', 'C', 'D']) + >>> # Create dataframe with index + >>> df = pd.DataFrame(np.random.randn(10, 4), + ... columns=['A', 'B', 'C', 'D']) - # Add another column of strings to the dataframe - df['Fruit'] = pd.Series(['apple', 'apple', 'grape', 'apple', 'apple', - 'grape', 'pear', 'pear', 'apple', 'pear']) + >>> # Add another column of strings to the dataframe + >>> df['Fruit'] = pd.Series(['apple', 'apple', 'grape', 'apple', 'apple', + ... 'grape', 'pear', 'pear', 'apple', 'pear']) - # Create scatterplot matrix - fig = create_scatterplotmatrix(df, diag='box', index='Fruit', height=1000, - width=1000) + >>> # Create scatterplot matrix + >>> fig = create_scatterplotmatrix(df, diag='box', index='Fruit', height=1000, + ... width=1000) + >>> fig.show() - # Plot - py.iplot(fig, filename = 'Scatterplot Matrix - Diagonal Styling') - ``` Example 4: Use a Theme to Style the Subplots - ``` - import plotly.plotly as py - from plotly.graph_objs import graph_objs - from plotly.figure_factory import create_scatterplotmatrix - import numpy as np - import pandas as pd + >>> from plotly.graph_objs import graph_objs + >>> from plotly.figure_factory import create_scatterplotmatrix - # Create dataframe with random data - df = pd.DataFrame(np.random.randn(100, 3), - columns=['A', 'B', 'C']) + >>> import numpy as np + >>> import pandas as pd - # Create scatterplot matrix using a built-in - # Plotly palette scale and indexing column 'A' - fig = create_scatterplotmatrix(df, diag='histogram', index='A', - colormap='Blues', height=800, width=800) + >>> # Create dataframe with random data + >>> df = pd.DataFrame(np.random.randn(100, 3), + ... columns=['A', 'B', 'C']) + + >>> # Create scatterplot matrix using a built-in + >>> # Plotly palette scale and indexing column 'A' + >>> fig = create_scatterplotmatrix(df, diag='histogram', index='A', + ... colormap='Blues', height=800, width=800) + >>> fig.show() - # Plot - py.iplot(fig, filename = 'Scatterplot Matrix - Colormap Theme') - ``` Example 5: Example 4 with Interval Factoring - ``` - import plotly.plotly as py - from plotly.graph_objs import graph_objs - from plotly.figure_factory import create_scatterplotmatrix - - import numpy as np - import pandas as pd - - # Create dataframe with random data - df = pd.DataFrame(np.random.randn(100, 3), - columns=['A', 'B', 'C']) - - # Create scatterplot matrix using a list of 2 rgb tuples - # and endpoints at -1, 0 and 1 - fig = create_scatterplotmatrix(df, diag='histogram', index='A', - colormap=['rgb(140, 255, 50)', - 'rgb(170, 60, 115)', '#6c4774', - (0.5, 0.1, 0.8)], - endpts=[-1, 0, 1], height=800, width=800) - - # Plot - py.iplot(fig, filename = 'Scatterplot Matrix - Intervals') - ``` + + >>> from plotly.graph_objs import graph_objs + >>> from plotly.figure_factory import create_scatterplotmatrix + + >>> import numpy as np + >>> import pandas as pd + + >>> # Create dataframe with random data + >>> df = pd.DataFrame(np.random.randn(100, 3), + ... columns=['A', 'B', 'C']) + + >>> # Create scatterplot matrix using a list of 2 rgb tuples + >>> # and endpoints at -1, 0 and 1 + >>> fig = create_scatterplotmatrix(df, diag='histogram', index='A', + ... colormap=['rgb(140, 255, 50)', + ... 'rgb(170, 60, 115)', '#6c4774', + ... (0.5, 0.1, 0.8)], + ... endpts=[-1, 0, 1], height=800, width=800) + >>> fig.show() + Example 6: Using the colormap as a Dictionary - ``` - import plotly.plotly as py - from plotly.graph_objs import graph_objs - from plotly.figure_factory import create_scatterplotmatrix - - import numpy as np - import pandas as pd - import random - - # Create dataframe with random data - df = pd.DataFrame(np.random.randn(100, 3), - columns=['Column A', - 'Column B', - 'Column C']) - - # Add new color column to dataframe - new_column = [] - strange_colors = ['turquoise', 'limegreen', 'goldenrod'] - - for j in range(100): - new_column.append(random.choice(strange_colors)) - df['Colors'] = pd.Series(new_column, index=df.index) - - # Create scatterplot matrix using a dictionary of hex color values - # which correspond to actual color names in 'Colors' column - fig = create_scatterplotmatrix( - df, diag='box', index='Colors', - colormap= dict( - turquoise = '#00F5FF', - limegreen = '#32CD32', - goldenrod = '#DAA520' - ), - colormap_type='cat', - height=800, width=800 - ) - - # Plot - py.iplot(fig, filename = 'Scatterplot Matrix - colormap dictionary ') - ``` + + >>> from plotly.graph_objs import graph_objs + >>> from plotly.figure_factory import create_scatterplotmatrix + + >>> import numpy as np + >>> import pandas as pd + >>> import random + + >>> # Create dataframe with random data + >>> df = pd.DataFrame(np.random.randn(100, 3), + ... columns=['Column A', + ... 'Column B', + ... 'Column C']) + + >>> # Add new color column to dataframe + >>> new_column = [] + >>> strange_colors = ['turquoise', 'limegreen', 'goldenrod'] + + >>> for j in range(100): + ... new_column.append(random.choice(strange_colors)) + >>> df['Colors'] = pd.Series(new_column, index=df.index) + + >>> # Create scatterplot matrix using a dictionary of hex color values + >>> # which correspond to actual color names in 'Colors' column + >>> fig = create_scatterplotmatrix( + ... df, diag='box', index='Colors', + ... colormap= dict( + ... turquoise = '#00F5FF', + ... limegreen = '#32CD32', + ... goldenrod = '#DAA520' + ... ), + ... colormap_type='cat', + ... height=800, width=800 + ... ) + >>> fig.show() """ # TODO: protected until #282 if dataframe is None: diff --git a/packages/python/plotly/plotly/figure_factory/_streamline.py b/packages/python/plotly/plotly/figure_factory/_streamline.py index 88a790d87fe..caf42d704e4 100644 --- a/packages/python/plotly/plotly/figure_factory/_streamline.py +++ b/packages/python/plotly/plotly/figure_factory/_streamline.py @@ -60,62 +60,53 @@ def create_streamline( :rtype (dict): returns a representation of streamline figure. Example 1: Plot simple streamline and increase arrow size - ``` - import plotly.plotly as py - from plotly.figure_factory import create_streamline - import numpy as np - import math + >>> from plotly.figure_factory import create_streamline + >>> import numpy as np + >>> import math - # Add data - x = np.linspace(-3, 3, 100) - y = np.linspace(-3, 3, 100) - Y, X = np.meshgrid(x, y) - u = -1 - X**2 + Y - v = 1 + X - Y**2 - u = u.T # Transpose - v = v.T # Transpose + >>> # Add data + >>> x = np.linspace(-3, 3, 100) + >>> y = np.linspace(-3, 3, 100) + >>> Y, X = np.meshgrid(x, y) + >>> u = -1 - X**2 + Y + >>> v = 1 + X - Y**2 + >>> u = u.T # Transpose + >>> v = v.T # Transpose - # Create streamline - fig = create_streamline(x, y, u, v, arrow_scale=.1) - - # Plot - py.plot(fig, filename='streamline') - ``` + >>> # Create streamline + >>> fig = create_streamline(x, y, u, v, arrow_scale=.1) + >>> fig.show() Example 2: from nbviewer.ipython.org/github/barbagroup/AeroPython - ``` - import plotly.plotly as py - from plotly.figure_factory import create_streamline - - import numpy as np - import math - - # Add data - N = 50 - x_start, x_end = -2.0, 2.0 - y_start, y_end = -1.0, 1.0 - x = np.linspace(x_start, x_end, N) - y = np.linspace(y_start, y_end, N) - X, Y = np.meshgrid(x, y) - ss = 5.0 - x_s, y_s = -1.0, 0.0 - - # Compute the velocity field on the mesh grid - u_s = ss/(2*np.pi) * (X-x_s)/((X-x_s)**2 + (Y-y_s)**2) - v_s = ss/(2*np.pi) * (Y-y_s)/((X-x_s)**2 + (Y-y_s)**2) - - # Create streamline - fig = create_streamline(x, y, u_s, v_s, density=2, name='streamline') - - # Add source point - point = Scatter(x=[x_s], y=[y_s], mode='markers', - marker=Marker(size=14), name='source point') - - # Plot - fig['data'].append(point) - py.plot(fig, filename='streamline') - ``` + + >>> from plotly.figure_factory import create_streamline + >>> import numpy as np + >>> import math + + >>> # Add data + >>> N = 50 + >>> x_start, x_end = -2.0, 2.0 + >>> y_start, y_end = -1.0, 1.0 + >>> x = np.linspace(x_start, x_end, N) + >>> y = np.linspace(y_start, y_end, N) + >>> X, Y = np.meshgrid(x, y) + >>> ss = 5.0 + >>> x_s, y_s = -1.0, 0.0 + + >>> # Compute the velocity field on the mesh grid + >>> u_s = ss/(2*np.pi) * (X-x_s)/((X-x_s)**2 + (Y-y_s)**2) + >>> v_s = ss/(2*np.pi) * (Y-y_s)/((X-x_s)**2 + (Y-y_s)**2) + + >>> # Create streamline + >>> fig = create_streamline(x, y, u_s, v_s, density=2, name='streamline') + + >>> # Add source point + >>> point = Scatter(x=[x_s], y=[y_s], mode='markers', + ... marker=Marker(size=14), name='source point') + + >>> fig['data'].append(point) + >>> fig.show() """ utils.validate_equal_length(x, y) utils.validate_equal_length(u, v) diff --git a/packages/python/plotly/plotly/figure_factory/_table.py b/packages/python/plotly/plotly/figure_factory/_table.py index c4570e2016a..8e3087410d0 100644 --- a/packages/python/plotly/plotly/figure_factory/_table.py +++ b/packages/python/plotly/plotly/figure_factory/_table.py @@ -58,52 +58,46 @@ def create_table( call help(plotly.graph_objs.Heatmap) Example 1: Simple Plotly Table - ``` - import plotly.plotly as py - from plotly.figure_factory import create_table - text = [['Country', 'Year', 'Population'], - ['US', 2000, 282200000], - ['Canada', 2000, 27790000], - ['US', 2010, 309000000], - ['Canada', 2010, 34000000]] + >>> from plotly.figure_factory import create_table - table = create_table(text) - py.iplot(table) - ``` + >>> text = [['Country', 'Year', 'Population'], + ... ['US', 2000, 282200000], + ... ['Canada', 2000, 27790000], + ... ['US', 2010, 309000000], + ... ['Canada', 2010, 34000000]] + + >>> table = create_table(text) + >>> table.show() Example 2: Table with Custom Coloring - ``` - import plotly.plotly as py - from plotly.figure_factory import create_table - - text = [['Country', 'Year', 'Population'], - ['US', 2000, 282200000], - ['Canada', 2000, 27790000], - ['US', 2010, 309000000], - ['Canada', 2010, 34000000]] - - table = create_table(text, - colorscale=[[0, '#000000'], - [.5, '#80beff'], - [1, '#cce5ff']], - font_colors=['#ffffff', '#000000', - '#000000']) - py.iplot(table) - ``` + + >>> from plotly.figure_factory import create_table + + >>> text = [['Country', 'Year', 'Population'], + ... ['US', 2000, 282200000], + ... ['Canada', 2000, 27790000], + ... ['US', 2010, 309000000], + ... ['Canada', 2010, 34000000]] + + >>> table = create_table(text, + ... colorscale=[[0, '#000000'], + ... [.5, '#80beff'], + ... [1, '#cce5ff']], + ... font_colors=['#ffffff', '#000000', + ... '#000000']) + >>> table.show() + Example 3: Simple Plotly Table with Pandas - ``` - import plotly.plotly as py - from plotly.figure_factory import create_table - import pandas as pd + >>> from plotly.figure_factory import create_table + >>> import pandas as pd - df = pd.read_csv('http://www.stat.ubc.ca/~jenny/notOcto/STAT545A/examples/gapminder/data/gapminderDataFiveYear.txt', sep='\t') - df_p = df[0:25] + >>> df = pd.read_csv('http://www.stat.ubc.ca/~jenny/notOcto/STAT545A/examples/gapminder/data/gapminderDataFiveYear.txt', sep='\t') + >>> df_p = df[0:25] - table_simple = create_table(df_p) - py.iplot(table_simple) - ``` + >>> table_simple = create_table(df_p) + >>> table_simple.show() """ # Avoiding mutables in the call signature diff --git a/packages/python/plotly/plotly/figure_factory/_ternary_contour.py b/packages/python/plotly/plotly/figure_factory/_ternary_contour.py index 52c7099bced..e48fea65673 100644 --- a/packages/python/plotly/plotly/figure_factory/_ternary_contour.py +++ b/packages/python/plotly/plotly/figure_factory/_ternary_contour.py @@ -574,40 +574,43 @@ def create_ternary_contour( Example 1: ternary contour plot with filled contours - # Define coordinates - a, b = np.mgrid[0:1:20j, 0:1:20j] - mask = a + b <= 1 - a = a[mask].ravel() - b = b[mask].ravel() - c = 1 - a - b - # Values to be displayed as contours - z = a * b * c - fig = ff.create_ternarycontour(np.stack((a, b, c)), z) + >>> import plotly.figure_factory as ff + >>> import numpy as np + >>> # Define coordinates + >>> a, b = np.mgrid[0:1:20j, 0:1:20j] + >>> mask = a + b <= 1 + >>> a = a[mask].ravel() + >>> b = b[mask].ravel() + >>> c = 1 - a - b + >>> # Values to be displayed as contours + >>> z = a * b * c + >>> fig = ff.create_ternarycontour(np.stack((a, b, c)), z) + >>> fig.show() It is also possible to give only two barycentric coordinates for each point, since the sum of the three coordinates is one: - fig = ff.create_ternarycontour(np.stack((a, b)), z) - plotly.iplot(fig) + >>> fig = ff.create_ternarycontour(np.stack((a, b)), z) + Example 2: ternary contour plot with line contours - fig = ff.create_ternarycontour(np.stack((a, b, c)), z, coloring='lines') + >>> fig = ff.create_ternarycontour(np.stack((a, b, c)), z, coloring='lines') Example 3: customize number of contours - fig = ff.create_ternarycontour(np.stack((a, b, c)), z, ncontours=8) + >>> fig = ff.create_ternarycontour(np.stack((a, b, c)), z, ncontours=8) Example 4: superimpose contour plot and original data as markers - fig = ff.create_ternarycontour(np.stack((a, b, c)), z, coloring='lines', + >>> fig = ff.create_ternarycontour(np.stack((a, b, c)), z, coloring='lines', showmarkers=True) Example 5: customize title and pole labels - fig = ff.create_ternarycontour(np.stack((a, b, c)), z, - title='Ternary plot', - pole_labels=['clay', 'quartz', 'fledspar']) + >>> fig = ff.create_ternarycontour(np.stack((a, b, c)), z, + ... title='Ternary plot', + ... pole_labels=['clay', 'quartz', 'fledspar']) """ if scipy_interp is None: raise ImportError( diff --git a/packages/python/plotly/plotly/figure_factory/_trisurf.py b/packages/python/plotly/plotly/figure_factory/_trisurf.py index 9efc255fbbd..caf7353d837 100644 --- a/packages/python/plotly/plotly/figure_factory/_trisurf.py +++ b/packages/python/plotly/plotly/figure_factory/_trisurf.py @@ -305,186 +305,166 @@ def create_trisurf( the x, y and z axes. 'x', 'y' and 'z' take (int|float) values Example 1: Sphere - ``` - # Necessary Imports for Trisurf - import numpy as np - from scipy.spatial import Delaunay - - import plotly.plotly as py - from plotly.figure_factory import create_trisurf - from plotly.graph_objs import graph_objs - - # Make data for plot - u = np.linspace(0, 2*np.pi, 20) - v = np.linspace(0, np.pi, 20) - u,v = np.meshgrid(u,v) - u = u.flatten() - v = v.flatten() - - x = np.sin(v)*np.cos(u) - y = np.sin(v)*np.sin(u) - z = np.cos(v) - - points2D = np.vstack([u,v]).T - tri = Delaunay(points2D) - simplices = tri.simplices - - # Create a figure - fig1 = create_trisurf(x=x, y=y, z=z, colormap="Rainbow", - simplices=simplices) - # Plot the data - py.iplot(fig1, filename='trisurf-plot-sphere') - ``` + + >>> # Necessary Imports for Trisurf + >>> import numpy as np + >>> from scipy.spatial import Delaunay + + >>> from plotly.figure_factory import create_trisurf + >>> from plotly.graph_objs import graph_objs + + >>> # Make data for plot + >>> u = np.linspace(0, 2*np.pi, 20) + >>> v = np.linspace(0, np.pi, 20) + >>> u,v = np.meshgrid(u,v) + >>> u = u.flatten() + >>> v = v.flatten() + + >>> x = np.sin(v)*np.cos(u) + >>> y = np.sin(v)*np.sin(u) + >>> z = np.cos(v) + + >>> points2D = np.vstack([u,v]).T + >>> tri = Delaunay(points2D) + >>> simplices = tri.simplices + + >>> # Create a figure + >>> fig1 = create_trisurf(x=x, y=y, z=z, colormap="Rainbow", + ... simplices=simplices) Example 2: Torus - ``` - # Necessary Imports for Trisurf - import numpy as np - from scipy.spatial import Delaunay - - import plotly.plotly as py - from plotly.figure_factory import create_trisurf - from plotly.graph_objs import graph_objs - - # Make data for plot - u = np.linspace(0, 2*np.pi, 20) - v = np.linspace(0, 2*np.pi, 20) - u,v = np.meshgrid(u,v) - u = u.flatten() - v = v.flatten() - - x = (3 + (np.cos(v)))*np.cos(u) - y = (3 + (np.cos(v)))*np.sin(u) - z = np.sin(v) - - points2D = np.vstack([u,v]).T - tri = Delaunay(points2D) - simplices = tri.simplices - - # Create a figure - fig1 = create_trisurf(x=x, y=y, z=z, colormap="Viridis", - simplices=simplices) - # Plot the data - py.iplot(fig1, filename='trisurf-plot-torus') - ``` + + >>> # Necessary Imports for Trisurf + >>> import numpy as np + >>> from scipy.spatial import Delaunay + + >>> from plotly.figure_factory import create_trisurf + >>> from plotly.graph_objs import graph_objs + + >>> # Make data for plot + >>> u = np.linspace(0, 2*np.pi, 20) + >>> v = np.linspace(0, 2*np.pi, 20) + >>> u,v = np.meshgrid(u,v) + >>> u = u.flatten() + >>> v = v.flatten() + + >>> x = (3 + (np.cos(v)))*np.cos(u) + >>> y = (3 + (np.cos(v)))*np.sin(u) + >>> z = np.sin(v) + + >>> points2D = np.vstack([u,v]).T + >>> tri = Delaunay(points2D) + >>> simplices = tri.simplices + + >>> # Create a figure + >>> fig1 = create_trisurf(x=x, y=y, z=z, colormap="Viridis", + ... simplices=simplices) Example 3: Mobius Band - ``` - # Necessary Imports for Trisurf - import numpy as np - from scipy.spatial import Delaunay - - import plotly.plotly as py - from plotly.figure_factory import create_trisurf - from plotly.graph_objs import graph_objs - - # Make data for plot - u = np.linspace(0, 2*np.pi, 24) - v = np.linspace(-1, 1, 8) - u,v = np.meshgrid(u,v) - u = u.flatten() - v = v.flatten() - - tp = 1 + 0.5*v*np.cos(u/2.) - x = tp*np.cos(u) - y = tp*np.sin(u) - z = 0.5*v*np.sin(u/2.) - - points2D = np.vstack([u,v]).T - tri = Delaunay(points2D) - simplices = tri.simplices - - # Create a figure - fig1 = create_trisurf(x=x, y=y, z=z, colormap=[(0.2, 0.4, 0.6), (1, 1, 1)], - simplices=simplices) - # Plot the data - py.iplot(fig1, filename='trisurf-plot-mobius-band') - ``` + + >>> # Necessary Imports for Trisurf + >>> import numpy as np + >>> from scipy.spatial import Delaunay + + >>> from plotly.figure_factory import create_trisurf + >>> from plotly.graph_objs import graph_objs + + >>> # Make data for plot + >>> u = np.linspace(0, 2*np.pi, 24) + >>> v = np.linspace(-1, 1, 8) + >>> u,v = np.meshgrid(u,v) + >>> u = u.flatten() + >>> v = v.flatten() + + >>> tp = 1 + 0.5*v*np.cos(u/2.) + >>> x = tp*np.cos(u) + >>> y = tp*np.sin(u) + >>> z = 0.5*v*np.sin(u/2.) + + >>> points2D = np.vstack([u,v]).T + >>> tri = Delaunay(points2D) + >>> simplices = tri.simplices + + >>> # Create a figure + >>> fig1 = create_trisurf(x=x, y=y, z=z, colormap=[(0.2, 0.4, 0.6), (1, 1, 1)], + ... simplices=simplices) Example 4: Using a Custom Colormap Function with Light Cone - ``` - # Necessary Imports for Trisurf - import numpy as np - from scipy.spatial import Delaunay - - import plotly.plotly as py - from plotly.figure_factory import create_trisurf - from plotly.graph_objs import graph_objs - - # Make data for plot - u=np.linspace(-np.pi, np.pi, 30) - v=np.linspace(-np.pi, np.pi, 30) - u,v=np.meshgrid(u,v) - u=u.flatten() - v=v.flatten() - - x = u - y = u*np.cos(v) - z = u*np.sin(v) - - points2D = np.vstack([u,v]).T - tri = Delaunay(points2D) - simplices = tri.simplices - - # Define distance function - def dist_origin(x, y, z): - return np.sqrt((1.0 * x)**2 + (1.0 * y)**2 + (1.0 * z)**2) - - # Create a figure - fig1 = create_trisurf(x=x, y=y, z=z, - colormap=['#FFFFFF', '#E4FFFE', - '#A4F6F9', '#FF99FE', - '#BA52ED'], - scale=[0, 0.6, 0.71, 0.89, 1], - simplices=simplices, - color_func=dist_origin) - # Plot the data - py.iplot(fig1, filename='trisurf-plot-custom-coloring') - ``` + + >>> # Necessary Imports for Trisurf + >>> import numpy as np + >>> from scipy.spatial import Delaunay + + >>> from plotly.figure_factory import create_trisurf + >>> from plotly.graph_objs import graph_objs + + >>> # Make data for plot + >>> u=np.linspace(-np.pi, np.pi, 30) + >>> v=np.linspace(-np.pi, np.pi, 30) + >>> u,v=np.meshgrid(u,v) + >>> u=u.flatten() + >>> v=v.flatten() + + >>> x = u + >>> y = u*np.cos(v) + >>> z = u*np.sin(v) + + >>> points2D = np.vstack([u,v]).T + >>> tri = Delaunay(points2D) + >>> simplices = tri.simplices + + >>> # Define distance function + >>> def dist_origin(x, y, z): + ... return np.sqrt((1.0 * x)**2 + (1.0 * y)**2 + (1.0 * z)**2) + + >>> # Create a figure + >>> fig1 = create_trisurf(x=x, y=y, z=z, + ... colormap=['#FFFFFF', '#E4FFFE', + ... '#A4F6F9', '#FF99FE', + ... '#BA52ED'], + ... scale=[0, 0.6, 0.71, 0.89, 1], + ... simplices=simplices, + ... color_func=dist_origin) Example 5: Enter color_func as a list of colors - ``` - # Necessary Imports for Trisurf - import numpy as np - from scipy.spatial import Delaunay - import random - - import plotly.plotly as py - from plotly.figure_factory import create_trisurf - from plotly.graph_objs import graph_objs - - # Make data for plot - u=np.linspace(-np.pi, np.pi, 30) - v=np.linspace(-np.pi, np.pi, 30) - u,v=np.meshgrid(u,v) - u=u.flatten() - v=v.flatten() - - x = u - y = u*np.cos(v) - z = u*np.sin(v) - - points2D = np.vstack([u,v]).T - tri = Delaunay(points2D) - simplices = tri.simplices - - - colors = [] - color_choices = ['rgb(0, 0, 0)', '#6c4774', '#d6c7dd'] - - for index in range(len(simplices)): - colors.append(random.choice(color_choices)) - - fig = create_trisurf( - x, y, z, simplices, - color_func=colors, - show_colorbar=True, - edges_color='rgb(2, 85, 180)', - title=' Modern Art' - ) - py.iplot(fig, filename="trisurf-plot-modern-art") - ``` + >>> # Necessary Imports for Trisurf + >>> import numpy as np + >>> from scipy.spatial import Delaunay + >>> import random + + >>> from plotly.figure_factory import create_trisurf + >>> from plotly.graph_objs import graph_objs + + >>> # Make data for plot + >>> u=np.linspace(-np.pi, np.pi, 30) + >>> v=np.linspace(-np.pi, np.pi, 30) + >>> u,v=np.meshgrid(u,v) + >>> u=u.flatten() + >>> v=v.flatten() + + >>> x = u + >>> y = u*np.cos(v) + >>> z = u*np.sin(v) + + >>> points2D = np.vstack([u,v]).T + >>> tri = Delaunay(points2D) + >>> simplices = tri.simplices + + + >>> colors = [] + >>> color_choices = ['rgb(0, 0, 0)', '#6c4774', '#d6c7dd'] + + >>> for index in range(len(simplices)): + >>> colors.append(random.choice(color_choices)) + + >>> fig = create_trisurf( + ... x, y, z, simplices, + ... color_func=colors, + ... show_colorbar=True, + ... edges_color='rgb(2, 85, 180)', + ... title=' Modern Art' + ... ) """ if aspectratio is None: aspectratio = {"x": 1, "y": 1, "z": 1} diff --git a/packages/python/plotly/plotly/figure_factory/_violin.py b/packages/python/plotly/plotly/figure_factory/_violin.py index 520a8fa5517..c2bc612cfce 100644 --- a/packages/python/plotly/plotly/figure_factory/_violin.py +++ b/packages/python/plotly/plotly/figure_factory/_violin.py @@ -487,98 +487,92 @@ def create_violin( :param (str) title: the title of the violin plot. Example 1: Single Violin Plot - ``` - import plotly.plotly as py - from plotly.figure_factory import create_violin - from plotly.graph_objs import graph_objs - import numpy as np - from scipy import stats + >>> from plotly.figure_factory import create_violin + >>> import plotly.graph_objs as graph_objects - # create list of random values - data_list = np.random.randn(100) - data_list.tolist() + >>> import numpy as np + >>> from scipy import stats - # create violin fig - fig = create_violin(data_list, colors='#604d9e') + >>> # create list of random values + >>> data_list = np.random.randn(100) + >>> data_list.tolist() - # plot - py.iplot(fig, filename='Violin Plot') - ``` + >>> # create violin fig + >>> fig = create_violin(data_list, colors='#604d9e') + + >>> # plot + >>> fig.show() Example 2: Multiple Violin Plots with Qualitative Coloring - ``` - import plotly.plotly as py - from plotly.figure_factory import create_violin - from plotly.graph_objs import graph_objs - - import numpy as np - import pandas as pd - from scipy import stats - - # create dataframe - np.random.seed(619517) - Nr=250 - y = np.random.randn(Nr) - gr = np.random.choice(list("ABCDE"), Nr) - norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)] - - for i, letter in enumerate("ABCDE"): - y[gr == letter] *=norm_params[i][1]+ norm_params[i][0] - df = pd.DataFrame(dict(Score=y, Group=gr)) - - # create violin fig - fig = create_violin(df, data_header='Score', group_header='Group', - sort=True, height=600, width=1000) - - # plot - py.iplot(fig, filename='Violin Plot with Coloring') - ``` + + >>> from plotly.figure_factory import create_violin + >>> import plotly.graph_objs as graph_objects + + >>> import numpy as np + >>> import pandas as pd + >>> from scipy import stats + + >>> # create dataframe + >>> np.random.seed(619517) + >>> Nr=250 + >>> y = np.random.randn(Nr) + >>> gr = np.random.choice(list("ABCDE"), Nr) + >>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)] + + >>> for i, letter in enumerate("ABCDE"): + ... y[gr == letter] *=norm_params[i][1]+ norm_params[i][0] + >>> df = pd.DataFrame(dict(Score=y, Group=gr)) + + >>> # create violin fig + >>> fig = create_violin(df, data_header='Score', group_header='Group', + ... sort=True, height=600, width=1000) + + >>> # plot + >>> fig.show() Example 3: Violin Plots with Colorscale - ``` - import plotly.plotly as py - from plotly.figure_factory import create_violin - from plotly.graph_objs import graph_objs - - import numpy as np - import pandas as pd - from scipy import stats - - # create dataframe - np.random.seed(619517) - Nr=250 - y = np.random.randn(Nr) - gr = np.random.choice(list("ABCDE"), Nr) - norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)] - - for i, letter in enumerate("ABCDE"): - y[gr == letter] *=norm_params[i][1]+ norm_params[i][0] - df = pd.DataFrame(dict(Score=y, Group=gr)) - - # define header params - data_header = 'Score' - group_header = 'Group' - - # make groupby object with pandas - group_stats = {} - groupby_data = df.groupby([group_header]) - - for group in "ABCDE": - data_from_group = groupby_data.get_group(group)[data_header] - # take a stat of the grouped data - stat = np.median(data_from_group) - # add to dictionary - group_stats[group] = stat - - # create violin fig - fig = create_violin(df, data_header='Score', group_header='Group', - height=600, width=1000, use_colorscale=True, - group_stats=group_stats) - - # plot - py.iplot(fig, filename='Violin Plot with Colorscale') - ``` + + >>> from plotly.figure_factory import create_violin + >>> import plotly.graph_objs as graph_objects + + >>> import numpy as np + >>> import pandas as pd + >>> from scipy import stats + + >>> # create dataframe + >>> np.random.seed(619517) + >>> Nr=250 + >>> y = np.random.randn(Nr) + >>> gr = np.random.choice(list("ABCDE"), Nr) + >>> norm_params=[(0, 1.2), (0.7, 1), (-0.5, 1.4), (0.3, 1), (0.8, 0.9)] + + >>> for i, letter in enumerate("ABCDE"): + ... y[gr == letter] *=norm_params[i][1]+ norm_params[i][0] + >>> df = pd.DataFrame(dict(Score=y, Group=gr)) + + >>> # define header params + >>> data_header = 'Score' + >>> group_header = 'Group' + + >>> # make groupby object with pandas + >>> group_stats = {} + >>> groupby_data = df.groupby([group_header]) + + >>> for group in "ABCDE": + ... data_from_group = groupby_data.get_group(group)[data_header] + ... # take a stat of the grouped data + ... stat = np.median(data_from_group) + ... # add to dictionary + ... group_stats[group] = stat + + >>> # create violin fig + >>> fig = create_violin(df, data_header='Score', group_header='Group', + ... height=600, width=1000, use_colorscale=True, + ... group_stats=group_stats) + + >>> # plot + >>> fig.show() """ # Validate colors diff --git a/packages/python/plotly/plotly/graph_objs/_figure.py b/packages/python/plotly/plotly/graph_objs/_figure.py index 4c2a0d295c0..942720030c4 100644 --- a/packages/python/plotly/plotly/graph_objs/_figure.py +++ b/packages/python/plotly/plotly/graph_objs/_figure.py @@ -857,6 +857,7 @@ def add_bar( Parameters ---------- + alignmentgroup Set several traces linked to the same position axis or matching axes to the same alignmentgroup. This controls @@ -4824,9 +4825,10 @@ def add_funnel( If True, associate this trace with the secondary y-axis of the subplot at the specified row and col. Only valid if all of the following conditions are satisfied: - * The figure was created using `plotly.subplots.make_subplots`. - * The row and col arguments are not None - * The subplot at the specified row and col has type xy + + * The figure was created using `plotly.subplots.make_subplots`. + * The row and col arguments are not None + * The subplot at the specified row and col has type xy (which is the default) and secondary_y True. These properties are specified in the specs argument to make_subplots. See the make_subplots docstring for more info. diff --git a/packages/python/plotly/plotly/io/_json.py b/packages/python/plotly/plotly/io/_json.py index f5b7fbb5a60..f67dbab3eb6 100644 --- a/packages/python/plotly/plotly/io/_json.py +++ b/packages/python/plotly/plotly/io/_json.py @@ -111,8 +111,7 @@ def from_json(value, output_type="Figure", skip_invalid=False): output_type: type or str (default 'Figure') The output figure type or type name. - One of: graph_objs.Figure, 'Figure', - graph_objs.FigureWidget, 'FigureWidget' + One of: graph_objs.Figure, 'Figure', graph_objs.FigureWidget, 'FigureWidget' skip_invalid: bool (default False) False if invalid figure properties should result in an exception. @@ -167,8 +166,7 @@ def read_json(file, output_type="Figure", skip_invalid=False): output_type: type or str (default 'Figure') The output figure type or type name. - One of: graph_objs.Figure, 'Figure', - graph_objs.FigureWidget, 'FigureWidget' + One of: graph_objs.Figure, 'Figure', graph_objs.FigureWidget, 'FigureWidget' skip_invalid: bool (default False) False if invalid figure properties should result in an exception. diff --git a/packages/python/plotly/plotly/io/_orca.py b/packages/python/plotly/plotly/io/_orca.py index ae4c25494f5..771259ed34b 100644 --- a/packages/python/plotly/plotly/io/_orca.py +++ b/packages/python/plotly/plotly/io/_orca.py @@ -1131,6 +1131,7 @@ def validate_executable(): >>> pio.orca.config.use_xvfb = True You can save this configuration for use in future sessions as follows: + >>> pio.orca.config.save() See https://www.x.org/releases/X11R7.6/doc/man/man1/Xvfb.1.xhtml diff --git a/packages/python/plotly/plotly/io/_templates.py b/packages/python/plotly/plotly/io/_templates.py index 9b8589c2af2..34110d09a02 100644 --- a/packages/python/plotly/plotly/io/_templates.py +++ b/packages/python/plotly/plotly/io/_templates.py @@ -213,6 +213,7 @@ def merge_templates(self, *args): Examples -------- + >>> pio.templates.merge_templates( ... go.layout.Template(layout={'font': {'size': 20}}), ... go.layout.Template(data={'scatter': [{'mode': 'markers'}]}), @@ -367,10 +368,12 @@ def to_templated(fig, skip=("title", "text")): Examples -------- Imports + >>> import plotly.graph_objs as go >>> import plotly.io as pio Construct a figure with large courier text + >>> fig = go.Figure(layout={'title': 'Figure Title', ... 'font': {'size': 20, 'family': 'Courier'}}) >>> fig @@ -382,6 +385,7 @@ def to_templated(fig, skip=("title", "text")): Convert to a figure with a template. Note how the 'font' properties have been moved into the template property. + >>> templated_fig = pio.to_templated(fig) >>> templated_fig Figure({ @@ -407,6 +411,7 @@ def to_templated(fig, skip=("title", "text")): The default font in fig2 will now be size 20 Courier. Next, register as a named template... + >>> pio.templates['large_courier'] = templated_fig.layout.template and specify this template by name when constructing a figure. @@ -434,7 +439,7 @@ def to_templated(fig, skip=("title", "text")): Returns ------- - figure + go.Figure """ # process fig diff --git a/packages/python/plotly/plotly/subplots.py b/packages/python/plotly/plotly/subplots.py index e158a42bfe6..63adab47e3a 100644 --- a/packages/python/plotly/plotly/subplots.py +++ b/packages/python/plotly/plotly/subplots.py @@ -230,11 +230,13 @@ def make_subplots( Examples -------- + Example 1: - # Stack two subplots vertically, and add a scatter trace to each + + >>> # Stack two subplots vertically, and add a scatter trace to each >>> from plotly.subplots import make_subplots ... import plotly.graph_objs as go - ... fig = tools.make_subplots(rows=2) + ... fig = make_subplots(rows=2) This is the format of your plot grid: [ (1,1) xaxis1,yaxis1 ] @@ -243,10 +245,11 @@ def make_subplots( >>> fig.add_scatter(y=[2, 1, 3], row=1, col=1) ... fig.add_scatter(y=[1, 3, 2], row=2, col=1) - # or see Figure.append_trace + or see Figure.append_trace Example 2: - # Stack a scatter plot + + >>> # Stack a scatter plot >>> fig = make_subplots(rows=2, shared_xaxes=True) This is the format of your plot grid: @@ -257,10 +260,11 @@ def make_subplots( ... fig.add_scatter(y=[1, 3, 2], row=2, col=1) Example 3: - # irregular subplot layout (more examples below under 'specs') - fig = tools.make_subplots(rows=2, cols=2, - specs=[[{}, {}], - [{'colspan': 2}, None]]) + + >>> # irregular subplot layout (more examples below under 'specs') + >>> fig = make_subplots(rows=2, cols=2, + specs=[[{}, {}], + [{'colspan': 2}, None]]) This is the format of your plot grid: [ (1,1) xaxis1,yaxis1 ] [ (1,2) xaxis2,yaxis2 ] @@ -271,7 +275,8 @@ def make_subplots( ... fig.add_trace(go.Scatter(x=[1,2,3], y=[2,1,2]), row=2, col=1) Example 4: - # insets + + >>> # insets >>> fig = make_subplots(insets=[{'cell': (1,1), 'l': 0.7, 'b': 0.3}]) This is the format of your plot grid: @@ -284,7 +289,8 @@ def make_subplots( ... fig.add_scatter(x=[1,2,3], y=[2,1,2], xaxis='x2', yaxis='y2') Example 5: - # include subplot titles + + >>> # include subplot titles >>> fig = make_subplots(rows=2, subplot_titles=('Plot 1','Plot 2')) This is the format of your plot grid: @@ -295,6 +301,7 @@ def make_subplots( >>> fig.add_bar(x=[1,2,3], y=[2,1,2], row=2, col=1) Example 6: + Subplot with mixed subplot types >>> fig = make_subplots(rows=2, cols=2,