def validate_annotated_heatmap(z, x, y, annotation_text): """ Annotated-heatmap-specific validations Check that if a text matrix is supplied, it has the same dimensions as the z matrix. See FigureFactory.create_annotated_heatmap() for params :raises: (PlotlyError) If z and text matrices do not have the same dimensions. """ if annotation_text is not None and isinstance(annotation_text, list): utils.validate_equal_length(z, annotation_text) for lst in range(len(z)): if len(z[lst]) != len(annotation_text[lst]): raise exceptions.PlotlyError("z and text should have the " "same dimensions") if x: if len(x) != len(z[0]): raise exceptions.PlotlyError("oops, the x list that you " "provided does not match the " "width of your z matrix ") if y: if len(y) != len(z): raise exceptions.PlotlyError("oops, the y list that you " "provided does not match the " "length of your z matrix ")
def create_ohlc(open, high, low, close, dates=None, direction="both", **kwargs): """ **deprecated**, use instead the plotly.graph_objects trace :class:`plotly.graph_objects.Ohlc` :param (list) open: opening values :param (list) high: high values :param (list) low: low values :param (list) close: closing :param (list) dates: list of datetime objects. Default: None :param (string) direction: direction can be 'increasing', 'decreasing', or 'both'. When the direction is 'increasing', the returned figure consists of all units where the close value is greater than the corresponding open value, and when the direction is 'decreasing', the returned figure consists of all units where the close value is less than or equal to the corresponding open value. When the direction is 'both', both increasing and decreasing units are returned. Default: 'both' :param kwargs: kwargs passed through plotly.graph_objs.Scatter. These kwargs describe other attributes about the ohlc Scatter trace such as the color or the legend name. For more information on valid kwargs call help(plotly.graph_objs.Scatter) :rtype (dict): returns a representation of an ohlc chart figure. Example 1: Simple OHLC chart from a Pandas DataFrame >>> from plotly.figure_factory import create_ohlc >>> from datetime import datetime >>> import pandas as pd >>> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv') >>> fig = create_ohlc(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'], dates=df.index) >>> fig.show() """ if dates is not None: utils.validate_equal_length(open, high, low, close, dates) else: utils.validate_equal_length(open, high, low, close) validate_ohlc(open, high, low, close, direction, **kwargs) if direction == "increasing": ohlc_incr = make_increasing_ohlc(open, high, low, close, dates, **kwargs) data = [ohlc_incr] elif direction == "decreasing": ohlc_decr = make_decreasing_ohlc(open, high, low, close, dates, **kwargs) data = [ohlc_decr] else: ohlc_incr = make_increasing_ohlc(open, high, low, close, dates, **kwargs) ohlc_decr = make_decreasing_ohlc(open, high, low, close, dates, **kwargs) data = [ohlc_incr, ohlc_decr] layout = graph_objs.Layout(xaxis=dict(zeroline=False), hovermode="closest") return graph_objs.Figure(data=data, layout=layout)
def create_candlestick(open, high, low, close, dates=None, direction="both", **kwargs): """ **deprecated**, use instead the plotly.graph_objects trace :class:`plotly.graph_objects.Candlestick` :param (list) open: opening values :param (list) high: high values :param (list) low: low values :param (list) close: closing values :param (list) dates: list of datetime objects. Default: None :param (string) direction: direction can be 'increasing', 'decreasing', or 'both'. When the direction is 'increasing', the returned figure consists of all candlesticks where the close value is greater than the corresponding open value, and when the direction is 'decreasing', the returned figure consists of all candlesticks where the close value is less than or equal to the corresponding open value. When the direction is 'both', both increasing and decreasing candlesticks are returned. Default: 'both' :param kwargs: kwargs passed through plotly.graph_objs.Scatter. These kwargs describe other attributes about the ohlc Scatter trace such as the color or the legend name. For more information on valid kwargs call help(plotly.graph_objs.Scatter) :rtype (dict): returns a representation of candlestick chart figure. Example 1: Simple candlestick chart from a Pandas DataFrame >>> from plotly.figure_factory import create_candlestick >>> from datetime import datetime >>> import pandas as pd >>> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv') >>> fig = create_candlestick(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'], ... dates=df.index) >>> fig.show() Example 2: Customize the candlestick colors >>> from plotly.figure_factory import create_candlestick >>> from plotly.graph_objs import Line, Marker >>> from datetime import datetime >>> import pandas as pd >>> df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv') >>> # Make increasing candlesticks and customize their color and name >>> fig_increasing = create_candlestick(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'], ... dates=df.index, ... direction='increasing', name='AAPL', ... marker=Marker(color='rgb(150, 200, 250)'), ... line=Line(color='rgb(150, 200, 250)')) >>> # Make decreasing candlesticks and customize their color and name >>> fig_decreasing = create_candlestick(df['AAPL.Open'], df['AAPL.High'], df['AAPL.Low'], df['AAPL.Close'], ... dates=df.index, ... direction='decreasing', ... marker=Marker(color='rgb(128, 128, 128)'), ... line=Line(color='rgb(128, 128, 128)')) >>> # Initialize the figure >>> fig = fig_increasing >>> # Add decreasing data with .extend() >>> fig.add_trace(fig_decreasing['data']) # doctest: +SKIP >>> fig.show() Example 3: Candlestick chart with datetime objects >>> 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) else: utils.validate_equal_length(open, high, low, close) validate_ohlc(open, high, low, close, direction, **kwargs) if direction == "increasing": candle_incr_data = make_increasing_candle(open, high, low, close, dates, **kwargs) data = candle_incr_data elif direction == "decreasing": candle_decr_data = make_decreasing_candle(open, high, low, close, dates, **kwargs) data = candle_decr_data else: candle_incr_data = make_increasing_candle(open, high, low, close, dates, **kwargs) candle_decr_data = make_decreasing_candle(open, high, low, close, dates, **kwargs) data = candle_incr_data + candle_decr_data layout = graph_objs.Layout() return graph_objs.Figure(data=data, layout=layout)
def create_streamline(x, y, u, v, density=1, angle=math.pi / 9, arrow_scale=.09, **kwargs): """ Returns data for a streamline plot. :param (list|ndarray) x: 1 dimensional, evenly spaced list or array :param (list|ndarray) y: 1 dimensional, evenly spaced list or array :param (ndarray) u: 2 dimensional array :param (ndarray) v: 2 dimensional array :param (float|int) density: controls the density of streamlines in plot. This is multiplied by 30 to scale similiarly to other available streamline functions such as matplotlib. Default = 1 :param (angle in radians) angle: angle of arrowhead. Default = pi/9 :param (float in [0,1]) arrow_scale: value to scale length of arrowhead Default = .09 :param kwargs: kwargs passed through plotly.graph_objs.Scatter for more information on valid kwargs call help(plotly.graph_objs.Scatter) :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 # 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') ``` 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') ``` """ utils.validate_equal_length(x, y) utils.validate_equal_length(u, v) validate_streamline(x, y) utils.validate_positive_scalars(density=density, arrow_scale=arrow_scale) streamline_x, streamline_y = _Streamline(x, y, u, v, density, angle, arrow_scale).sum_streamlines() arrow_x, arrow_y = _Streamline(x, y, u, v, density, angle, arrow_scale).get_streamline_arrows() streamline = graph_objs.Scatter(x=streamline_x + arrow_x, y=streamline_y + arrow_y, mode='lines', **kwargs) data = [streamline] layout = graph_objs.Layout(hovermode='closest') return graph_objs.Figure(data=data, layout=layout)
def create_quiver(x, y, u, v, scale=.1, arrow_scale=.3, angle=math.pi / 9, scaleratio=None, **kwargs): """ Returns data for a quiver plot. :param (list|ndarray) x: x coordinates of the arrow locations :param (list|ndarray) y: y coordinates of the arrow locations :param (list|ndarray) u: x components of the arrow vectors :param (list|ndarray) v: y components of the arrow vectors :param (float in [0,1]) scale: scales size of the arrows(ideally to avoid overlap). Default = .1 :param (float in [0,1]) arrow_scale: value multiplied to length of barb to get length of arrowhead. Default = .3 :param (angle in radians) angle: angle of arrowhead. Default = pi/9 :param (positive float) scaleratio: the ratio between the scale of the y-axis and the scale of the x-axis (scale_y / scale_x). Default = None, the scale ratio is not fixed. :param kwargs: kwargs passed through plotly.graph_objs.Scatter for more information on valid kwargs call help(plotly.graph_objs.Scatter) :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 # 1 Arrow from (0,0) to (1,1) fig = create_quiver(x=[0], y=[0], u=[1], v=[1], scale=1) 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 # 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) # 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 # 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') # 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') ``` """ utils.validate_equal_length(x, y, u, v) utils.validate_positive_scalars(arrow_scale=arrow_scale, scale=scale) if scaleratio is None: quiver_obj = _Quiver(x, y, u, v, scale, arrow_scale, angle) else: quiver_obj = _Quiver(x, y, u, v, scale, arrow_scale, angle, scaleratio) barb_x, barb_y = quiver_obj.get_barbs() arrow_x, arrow_y = quiver_obj.get_quiver_arrows() quiver_plot = graph_objs.Scatter(x=barb_x + arrow_x, y=barb_y + arrow_y, mode='lines', **kwargs) data = [quiver_plot] if scaleratio is None: layout = graph_objs.Layout(hovermode='closest') else: layout = graph_objs.Layout( hovermode='closest', yaxis=dict( scaleratio = scaleratio, scaleanchor = "x" ) ) return graph_objs.Figure(data=data, layout=layout)
def create_candlestick(open, high, low, close, dates=None, direction="both", **kwargs): """ BETA function that creates a candlestick chart :param (list) open: opening values :param (list) high: high values :param (list) low: low values :param (list) close: closing values :param (list) dates: list of datetime objects. Default: None :param (string) direction: direction can be 'increasing', 'decreasing', or 'both'. When the direction is 'increasing', the returned figure consists of all candlesticks where the close value is greater than the corresponding open value, and when the direction is 'decreasing', the returned figure consists of all candlesticks where the close value is less than or equal to the corresponding open value. When the direction is 'both', both increasing and decreasing candlesticks are returned. Default: 'both' :param kwargs: kwargs passed through plotly.graph_objs.Scatter. These kwargs describe other attributes about the ohlc Scatter trace such as the color or the legend name. For more information on valid kwargs call help(plotly.graph_objs.Scatter) :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 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) ``` 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({ 'title': 'The Great Recession', 'yaxis': {'title': 'AAPL Stock'}, 'shapes': [{ 'x0': '2007-12-01', 'x1': '2007-12-01', 'y0': 0, 'y1': 1, 'xref': 'x', 'yref': 'paper', 'line': {'color': 'rgb(30,30,30)', 'width': 1} }], 'annotations': [{ 'x': '2007-12-01', 'y': 0.05, 'xref': 'x', 'yref': 'paper', 'showarrow': False, 'xanchor': 'left', 'text': 'Official start of the recession' }] }) py.plot(fig, filename='finance/aapl-recession-candlestick', validate=False) ``` 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 df = web.DataReader("aapl", 'yahoo', datetime(2008, 1, 1), datetime(2009, 4, 1)) # 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)')) # 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)')) # Initialize the figure fig = fig_increasing # Add decreasing data with .extend() fig['data'].extend(fig_decreasing['data']) py.iplot(fig, filename='finance/aapl-candlestick-custom', validate=False) ``` 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) ``` """ if dates is not None: utils.validate_equal_length(open, high, low, close, dates) else: utils.validate_equal_length(open, high, low, close) validate_ohlc(open, high, low, close, direction, **kwargs) if direction is "increasing": candle_incr_data = make_increasing_candle(open, high, low, close, dates, **kwargs) data = candle_incr_data elif direction is "decreasing": candle_decr_data = make_decreasing_candle(open, high, low, close, dates, **kwargs) data = candle_decr_data else: candle_incr_data = make_increasing_candle(open, high, low, close, dates, **kwargs) candle_decr_data = make_decreasing_candle(open, high, low, close, dates, **kwargs) data = candle_incr_data + candle_decr_data layout = graph_objs.Layout() return graph_objs.Figure(data=data, layout=layout)
def create_streamline(x, y, u, v, density=1, angle=math.pi / 9, arrow_scale=0.09, **kwargs): """ Returns data for a streamline plot. :param (list|ndarray) x: 1 dimensional, evenly spaced list or array :param (list|ndarray) y: 1 dimensional, evenly spaced list or array :param (ndarray) u: 2 dimensional array :param (ndarray) v: 2 dimensional array :param (float|int) density: controls the density of streamlines in plot. This is multiplied by 30 to scale similiarly to other available streamline functions such as matplotlib. Default = 1 :param (angle in radians) angle: angle of arrowhead. Default = pi/9 :param (float in [0,1]) arrow_scale: value to scale length of arrowhead Default = .09 :param kwargs: kwargs passed through plotly.graph_objs.Scatter for more information on valid kwargs call help(plotly.graph_objs.Scatter) :rtype (dict): returns a representation of streamline figure. Example 1: Plot simple streamline and increase arrow size >>> from plotly.figure_factory import create_streamline >>> import plotly.graph_objects as go >>> 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 >>> # Create streamline >>> fig = create_streamline(x, y, u, v, arrow_scale=.1) >>> fig.show() Example 2: from nbviewer.ipython.org/github/barbagroup/AeroPython >>> 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 = go.Scatter(x=[x_s], y=[y_s], mode='markers', ... marker_size=14, name='source point') >>> fig.add_trace(point) # doctest: +SKIP >>> fig.show() """ utils.validate_equal_length(x, y) utils.validate_equal_length(u, v) validate_streamline(x, y) utils.validate_positive_scalars(density=density, arrow_scale=arrow_scale) streamline_x, streamline_y = _Streamline(x, y, u, v, density, angle, arrow_scale).sum_streamlines() arrow_x, arrow_y = _Streamline(x, y, u, v, density, angle, arrow_scale).get_streamline_arrows() streamline = graph_objs.Scatter(x=streamline_x + arrow_x, y=streamline_y + arrow_y, mode="lines", **kwargs) data = [streamline] layout = graph_objs.Layout(hovermode="closest") return graph_objs.Figure(data=data, layout=layout)
def create_candlestick(open, high, low, close, dates=None, direction='both', **kwargs): """ BETA function that creates a candlestick chart :param (list) open: opening values :param (list) high: high values :param (list) low: low values :param (list) close: closing values :param (list) dates: list of datetime objects. Default: None :param (string) direction: direction can be 'increasing', 'decreasing', or 'both'. When the direction is 'increasing', the returned figure consists of all candlesticks where the close value is greater than the corresponding open value, and when the direction is 'decreasing', the returned figure consists of all candlesticks where the close value is less than or equal to the corresponding open value. When the direction is 'both', both increasing and decreasing candlesticks are returned. Default: 'both' :param kwargs: kwargs passed through plotly.graph_objs.Scatter. These kwargs describe other attributes about the ohlc Scatter trace such as the color or the legend name. For more information on valid kwargs call help(plotly.graph_objs.Scatter) :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 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) ``` 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({ 'title': 'The Great Recession', 'yaxis': {'title': 'AAPL Stock'}, 'shapes': [{ 'x0': '2007-12-01', 'x1': '2007-12-01', 'y0': 0, 'y1': 1, 'xref': 'x', 'yref': 'paper', 'line': {'color': 'rgb(30,30,30)', 'width': 1} }], 'annotations': [{ 'x': '2007-12-01', 'y': 0.05, 'xref': 'x', 'yref': 'paper', 'showarrow': False, 'xanchor': 'left', 'text': 'Official start of the recession' }] }) py.plot(fig, filename='finance/aapl-recession-candlestick', validate=False) ``` 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 df = web.DataReader("aapl", 'yahoo', datetime(2008, 1, 1), datetime(2009, 4, 1)) # 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)')) # 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)')) # Initialize the figure fig = fig_increasing # Add decreasing data with .extend() fig['data'].extend(fig_decreasing['data']) py.iplot(fig, filename='finance/aapl-candlestick-custom', validate=False) ``` 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) ``` """ if dates is not None: utils.validate_equal_length(open, high, low, close, dates) else: utils.validate_equal_length(open, high, low, close) validate_ohlc(open, high, low, close, direction, **kwargs) if direction is 'increasing': candle_incr_data = make_increasing_candle(open, high, low, close, dates, **kwargs) data = candle_incr_data elif direction is 'decreasing': candle_decr_data = make_decreasing_candle(open, high, low, close, dates, **kwargs) data = candle_decr_data else: candle_incr_data = make_increasing_candle(open, high, low, close, dates, **kwargs) candle_decr_data = make_decreasing_candle(open, high, low, close, dates, **kwargs) data = candle_incr_data + candle_decr_data layout = graph_objs.Layout() return graph_objs.Figure(data=data, layout=layout)
def create_quiver(x, y, u, v, scale=.1, arrow_scale=.3, angle=math.pi / 9, **kwargs): """ Returns data for a quiver plot. :param (list|ndarray) x: x coordinates of the arrow locations :param (list|ndarray) y: y coordinates of the arrow locations :param (list|ndarray) u: x components of the arrow vectors :param (list|ndarray) v: y components of the arrow vectors :param (float in [0,1]) scale: scales size of the arrows(ideally to avoid overlap). Default = .1 :param (float in [0,1]) arrow_scale: value multiplied to length of barb to get length of arrowhead. Default = .3 :param (angle in radians) angle: angle of arrowhead. Default = pi/9 :param kwargs: kwargs passed through plotly.graph_objs.Scatter for more information on valid kwargs call help(plotly.graph_objs.Scatter) :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 # 1 Arrow from (0,0) to (1,1) fig = create_quiver(x=[0], y=[0], u=[1], v=[1], scale=1) 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 # 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) # 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 # Create quiver fig = create_quiver(x, y, u, v, scale=.2, arrow_scale=.3, angle=math.pi/6, name='Wind Velocity', line=Line(width=1)) # Add title to layout fig['layout'].update(title='Quiver Plot') # Plot py.plot(fig, filename='quiver') ``` """ utils.validate_equal_length(x, y, u, v) utils.validate_positive_scalars(arrow_scale=arrow_scale, scale=scale) barb_x, barb_y = _Quiver(x, y, u, v, scale, arrow_scale, angle).get_barbs() arrow_x, arrow_y = _Quiver(x, y, u, v, scale, arrow_scale, angle).get_quiver_arrows() quiver = graph_objs.Scatter(x=barb_x + arrow_x, y=barb_y + arrow_y, mode='lines', **kwargs) data = [quiver] layout = graph_objs.Layout(hovermode='closest') return graph_objs.Figure(data=data, layout=layout)
def create_ohlc(open, high, low, close, dates=None, direction="both", **kwargs): """ BETA function that creates an ohlc chart :param (list) open: opening values :param (list) high: high values :param (list) low: low values :param (list) close: closing :param (list) dates: list of datetime objects. Default: None :param (string) direction: direction can be 'increasing', 'decreasing', or 'both'. When the direction is 'increasing', the returned figure consists of all units where the close value is greater than the corresponding open value, and when the direction is 'decreasing', the returned figure consists of all units where the close value is less than or equal to the corresponding open value. When the direction is 'both', both increasing and decreasing units are returned. Default: 'both' :param kwargs: kwargs passed through plotly.graph_objs.Scatter. These kwargs describe other attributes about the ohlc Scatter trace such as the color or the legend name. For more information on valid kwargs call help(plotly.graph_objs.Scatter) :rtype (dict): returns a representation of an ohlc chart figure. Example 1: Simple OHLC chart from a Pandas DataFrame >>> 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) >>> fig.show() Example 2: Add text and annotations to the OHLC chart >>> 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 >>> 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)) >>> # 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)')) >>> # Initialize the figure >>> fig = fig_increasing >>> # Add decreasing data with .extend() >>> fig['data'].extend(fig_decreasing['data']) >>> fig.show() Example 4: OHLC chart with datetime objects >>> 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) else: utils.validate_equal_length(open, high, low, close) validate_ohlc(open, high, low, close, direction, **kwargs) if direction is "increasing": ohlc_incr = make_increasing_ohlc(open, high, low, close, dates, **kwargs) data = [ohlc_incr] elif direction is "decreasing": ohlc_decr = make_decreasing_ohlc(open, high, low, close, dates, **kwargs) data = [ohlc_decr] else: ohlc_incr = make_increasing_ohlc(open, high, low, close, dates, **kwargs) ohlc_decr = make_decreasing_ohlc(open, high, low, close, dates, **kwargs) data = [ohlc_incr, ohlc_decr] layout = graph_objs.Layout(xaxis=dict(zeroline=False), hovermode="closest") return graph_objs.Figure(data=data, layout=layout)
def create_distplot( hist_data, group_labels, bin_size=1.0, curve_type="kde", colors=None, rug_text=None, histnorm=DEFAULT_HISTNORM, show_hist=True, show_curve=True, show_rug=True, ): """ BETA function that creates a distplot similar to seaborn.distplot The distplot can be composed of all or any combination of the following 3 components: (1) histogram, (2) curve: (a) kernel density estimation or (b) normal curve, and (3) rug plot. Additionally, multiple distplots (from multiple datasets) can be created in the same plot. :param (list[list]) hist_data: Use list of lists to plot multiple data sets on the same plot. :param (list[str]) group_labels: Names for each data set. :param (list[float]|float) bin_size: Size of histogram bins. Default = 1. :param (str) curve_type: 'kde' or 'normal'. Default = 'kde' :param (str) histnorm: 'probability density' or 'probability' Default = 'probability density' :param (bool) show_hist: Add histogram to distplot? Default = True :param (bool) show_curve: Add curve to distplot? Default = True :param (bool) show_rug: Add rug to distplot? Default = True :param (list[str]) colors: Colors for traces. :param (list[list]) rug_text: Hovertext values for rug_plot, :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]] group_labels = ['distplot example'] 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] # Group data together hist_data = [hist1_x, hist2_x] group_labels = ['2012', '2013'] # 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'] # 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) # Add title fig['layout'].update(title='Dist Plot') # 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 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'] 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) ``` """ if colors is None: colors = [] if rug_text is None: rug_text = [] validate_distplot(hist_data, curve_type) utils.validate_equal_length(hist_data, group_labels) if isinstance(bin_size, (float, int)): bin_size = [bin_size] * len(hist_data) hist = _Distplot( hist_data, histnorm, group_labels, bin_size, curve_type, colors, rug_text, show_hist, show_curve, ).make_hist() if curve_type == "normal": curve = _Distplot( hist_data, histnorm, group_labels, bin_size, curve_type, colors, rug_text, show_hist, show_curve, ).make_normal() else: curve = _Distplot( hist_data, histnorm, group_labels, bin_size, curve_type, colors, rug_text, show_hist, show_curve, ).make_kde() rug = _Distplot( hist_data, histnorm, group_labels, bin_size, curve_type, colors, rug_text, show_hist, show_curve, ).make_rug() data = [] if show_hist: data.append(hist) if show_curve: data.append(curve) if show_rug: data.append(rug) layout = graph_objs.Layout( barmode="overlay", hovermode="closest", legend=dict(traceorder="reversed"), xaxis1=dict(domain=[0.0, 1.0], anchor="y2", zeroline=False), yaxis1=dict(domain=[0.35, 1], anchor="free", position=0.0), yaxis2=dict(domain=[0, 0.25], anchor="x1", dtick=1, showticklabels=False), ) else: layout = graph_objs.Layout( barmode="overlay", hovermode="closest", legend=dict(traceorder="reversed"), xaxis1=dict(domain=[0.0, 1.0], anchor="y2", zeroline=False), yaxis1=dict(domain=[0.0, 1], anchor="free", position=0.0), ) data = sum(data, []) return graph_objs.Figure(data=data, layout=layout)
def create_distplot(hist_data, group_labels, bin_size=1., curve_type='kde', colors=None, rug_text=None, histnorm=DEFAULT_HISTNORM, show_hist=True, show_curve=True, show_rug=True): """ BETA function that creates a distplot similar to seaborn.distplot The distplot can be composed of all or any combination of the following 3 components: (1) histogram, (2) curve: (a) kernel density estimation or (b) normal curve, and (3) rug plot. Additionally, multiple distplots (from multiple datasets) can be created in the same plot. :param (list[list]) hist_data: Use list of lists to plot multiple data sets on the same plot. :param (list[str]) group_labels: Names for each data set. :param (list[float]|float) bin_size: Size of histogram bins. Default = 1. :param (str) curve_type: 'kde' or 'normal'. Default = 'kde' :param (str) histnorm: 'probability density' or 'probability' Default = 'probability density' :param (bool) show_hist: Add histogram to distplot? Default = True :param (bool) show_curve: Add curve to distplot? Default = True :param (bool) show_rug: Add rug to distplot? Default = True :param (list[str]) colors: Colors for traces. :param (list[list]) rug_text: Hovertext values for rug_plot, :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]] group_labels = ['distplot example'] 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] # Group data together hist_data = [hist1_x, hist2_x] group_labels = ['2012', '2013'] # 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'] # 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) # Add title fig['layout'].update(title='Dist Plot') # 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 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'] 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) ``` """ if colors is None: colors = [] if rug_text is None: rug_text = [] validate_distplot(hist_data, curve_type) utils.validate_equal_length(hist_data, group_labels) if isinstance(bin_size, (float, int)): bin_size = [bin_size] * len(hist_data) hist = _Distplot( hist_data, histnorm, group_labels, bin_size, curve_type, colors, rug_text, show_hist, show_curve).make_hist() if curve_type == 'normal': curve = _Distplot( hist_data, histnorm, group_labels, bin_size, curve_type, colors, rug_text, show_hist, show_curve).make_normal() else: curve = _Distplot( hist_data, histnorm, group_labels, bin_size, curve_type, colors, rug_text, show_hist, show_curve).make_kde() rug = _Distplot( hist_data, histnorm, group_labels, bin_size, curve_type, colors, rug_text, show_hist, show_curve).make_rug() data = [] if show_hist: data.append(hist) if show_curve: data.append(curve) if show_rug: data.append(rug) layout = graph_objs.Layout( barmode='overlay', hovermode='closest', legend=dict(traceorder='reversed'), xaxis1=dict(domain=[0.0, 1.0], anchor='y2', zeroline=False), yaxis1=dict(domain=[0.35, 1], anchor='free', position=0.0), yaxis2=dict(domain=[0, 0.25], anchor='x1', dtick=1, showticklabels=False)) else: layout = graph_objs.Layout( barmode='overlay', hovermode='closest', legend=dict(traceorder='reversed'), xaxis1=dict(domain=[0.0, 1.0], anchor='y2', zeroline=False), yaxis1=dict(domain=[0., 1], anchor='free', position=0.0)) data = sum(data, []) return graph_objs.Figure(data=data, layout=layout)
def create_distplot( hist_data, group_labels, bin_size=1.0, curve_type="kde", colors=None, rug_text=None, histnorm=DEFAULT_HISTNORM, show_hist=True, show_curve=True, show_rug=True, ): """ Function that creates a distplot similar to seaborn.distplot; **this function is deprecated**, use instead :mod:`plotly.express` functions, for example >>> import plotly.express as px >>> tips = px.data.tips() >>> fig = px.histogram(tips, x="total_bill", y="tip", color="sex", marginal="rug", ... hover_data=tips.columns) >>> fig.show() The distplot can be composed of all or any combination of the following 3 components: (1) histogram, (2) curve: (a) kernel density estimation or (b) normal curve, and (3) rug plot. Additionally, multiple distplots (from multiple datasets) can be created in the same plot. :param (list[list]) hist_data: Use list of lists to plot multiple data sets on the same plot. :param (list[str]) group_labels: Names for each data set. :param (list[float]|float) bin_size: Size of histogram bins. Default = 1. :param (str) curve_type: 'kde' or 'normal'. Default = 'kde' :param (str) histnorm: 'probability density' or 'probability' Default = 'probability density' :param (bool) show_hist: Add histogram to distplot? Default = True :param (bool) show_curve: Add curve to distplot? Default = True :param (bool) show_rug: Add rug to distplot? Default = True :param (list[str]) colors: Colors for traces. :param (list[list]) rug_text: Hovertext values for rug_plot, :return (dict): Representation of a distplot figure. Example 1: Simple distplot of 1 data set >>> 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]] >>> group_labels = ['distplot example'] >>> fig = create_distplot(hist_data, group_labels) >>> fig.show() Example 2: Two data sets and added rug text >>> 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_labels = ['2012', '2013'] >>> # 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'] >>> # 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) >>> # Add title >>> fig.update_layout(title='Dist Plot') # doctest: +SKIP >>> fig.show() Example 3: Plot with normal curve and hide rug plot >>> 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 >>> 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) Example 4: Distplot with Pandas >>> 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 = [] if rug_text is None: rug_text = [] validate_distplot(hist_data, curve_type) utils.validate_equal_length(hist_data, group_labels) if isinstance(bin_size, (float, int)): bin_size = [bin_size] * len(hist_data) data = [] if show_hist: hist = _Distplot( hist_data, histnorm, group_labels, bin_size, curve_type, colors, rug_text, show_hist, show_curve, ).make_hist() data.append(hist) if show_curve: if curve_type == "normal": curve = _Distplot( hist_data, histnorm, group_labels, bin_size, curve_type, colors, rug_text, show_hist, show_curve, ).make_normal() else: curve = _Distplot( hist_data, histnorm, group_labels, bin_size, curve_type, colors, rug_text, show_hist, show_curve, ).make_kde() data.append(curve) if show_rug: rug = _Distplot( hist_data, histnorm, group_labels, bin_size, curve_type, colors, rug_text, show_hist, show_curve, ).make_rug() data.append(rug) layout = graph_objs.Layout( barmode="overlay", hovermode="closest", legend=dict(traceorder="reversed"), xaxis1=dict(domain=[0.0, 1.0], anchor="y2", zeroline=False), yaxis1=dict(domain=[0.35, 1], anchor="free", position=0.0), yaxis2=dict(domain=[0, 0.25], anchor="x1", dtick=1, showticklabels=False), ) else: layout = graph_objs.Layout( barmode="overlay", hovermode="closest", legend=dict(traceorder="reversed"), xaxis1=dict(domain=[0.0, 1.0], anchor="y2", zeroline=False), yaxis1=dict(domain=[0.0, 1], anchor="free", position=0.0), ) data = sum(data, []) return graph_objs.Figure(data=data, layout=layout)
def create_quiver(x, y, u, v, scale=0.1, arrow_scale=0.3, angle=math.pi / 9, scaleratio=None, **kwargs): """ Returns data for a quiver plot. :param (list|ndarray) x: x coordinates of the arrow locations :param (list|ndarray) y: y coordinates of the arrow locations :param (list|ndarray) u: x components of the arrow vectors :param (list|ndarray) v: y components of the arrow vectors :param (float in [0,1]) scale: scales size of the arrows(ideally to avoid overlap). Default = .1 :param (float in [0,1]) arrow_scale: value multiplied to length of barb to get length of arrowhead. Default = .3 :param (angle in radians) angle: angle of arrowhead. Default = pi/9 :param (positive float) scaleratio: the ratio between the scale of the y-axis and the scale of the x-axis (scale_y / scale_x). Default = None, the scale ratio is not fixed. :param kwargs: kwargs passed through plotly.graph_objs.Scatter for more information on valid kwargs call help(plotly.graph_objs.Scatter) :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 # 1 Arrow from (0,0) to (1,1) fig = create_quiver(x=[0], y=[0], u=[1], v=[1], scale=1) 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 # 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) # 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 # 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') # 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') ``` """ utils.validate_equal_length(x, y, u, v) utils.validate_positive_scalars(arrow_scale=arrow_scale, scale=scale) if scaleratio is None: quiver_obj = _Quiver(x, y, u, v, scale, arrow_scale, angle) else: quiver_obj = _Quiver(x, y, u, v, scale, arrow_scale, angle, scaleratio) barb_x, barb_y = quiver_obj.get_barbs() arrow_x, arrow_y = quiver_obj.get_quiver_arrows() quiver_plot = graph_objs.Scatter(x=barb_x + arrow_x, y=barb_y + arrow_y, mode="lines", **kwargs) data = [quiver_plot] if scaleratio is None: layout = graph_objs.Layout(hovermode="closest") else: layout = graph_objs.Layout(hovermode="closest", yaxis=dict(scaleratio=scaleratio, scaleanchor="x")) return graph_objs.Figure(data=data, layout=layout)