plotly.figure_factory package¶
-
plotly.figure_factory.
create_2d_density
(x, y, colorscale='Earth', ncontours=20, hist_color=(0, 0, 0.5), point_color=(0, 0, 0.5), point_size=2, title='2D Density Plot', height=600, width=600)¶ deprecated, use instead
plotly.express.density_heatmap()
.- Parameters
x ((list|array)) – x-axis data for plot generation
y ((list|array)) – y-axis data for plot generation
colorscale ((str|tuple|list)) – either a plotly scale name, an rgb or hex color, a color tuple or a list or tuple of colors. An rgb color is of the form ‘rgb(x, y, z)’ where x, y, z belong to the interval [0, 255] and a color tuple is a tuple of the form (a, b, c) where a, b and c belong to [0, 1]. If colormap is a list, it must contain the valid color types aforementioned as its members.
ncontours ((int)) – the number of 2D contours to draw on the plot
hist_color ((str)) – the color of the plotted histograms
point_color ((str)) – the color of the scatter points
point_size ((str)) – the color of the scatter points
title ((str)) – set the title for the plot
height ((float)) – the height of the chart
width ((float)) – the width of the chart
Examples
Example 1: Simple 2D Density Plot
>>> from plotly.figure_factory import 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))
>>> # Create a figure >>> fig = create_2d_density(x, y)
>>> # Plot the data >>> fig.show()
Example 2: Using Parameters
>>> from plotly.figure_factory import 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))
>>> # 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)
>>> # Plot the data >>> fig.show()
-
plotly.figure_factory.
create_annotated_heatmap
(z, x=None, y=None, annotation_text=None, colorscale='Plasma', font_colors=None, showscale=False, reversescale=False, **kwargs)¶ deprecated, use instead
plotly.express.imshow()
.Function that creates annotated heatmaps
This function adds annotations to each cell of the heatmap.
- Parameters
x ((list)) – x axis labels.
y ((list)) – y axis labels.
annotation_text ((list[list]|ndarray)) – Text strings for annotations. Should have the same dimensions as the z matrix. If no text is added, the values of the z matrix are annotated. Default = z matrix values.
colorscale ((list|str)) – heatmap colorscale.
font_colors ((list)) – List of two color strings: [min_text_color, max_text_color] where min_text_color is applied to annotations for heatmap values < (max_value - min_value)/2. If font_colors is not defined, the colors are defined logically as black or white depending on the heatmap’s colorscale.
showscale ((bool)) – Display colorscale. Default = False
reversescale ((bool)) – Reverse colorscale. Default = False
kwargs – kwargs passed through plotly.graph_objects.Heatmap. These kwargs describe other attributes about the annotated Heatmap trace such as the colorscale. For more information on valid kwargs call help(plotly.graph_objects.Heatmap)
Example 1: Simple annotated heatmap with default configuration
>>> 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]]
>>> fig = ff.create_annotated_heatmap(z) >>> fig.show()
-
plotly.figure_factory.
create_bullet
(data, markers=None, measures=None, ranges=None, subtitles=None, titles=None, orientation='h', range_colors=('rgb(200, 200, 200)', 'rgb(245, 245, 245)'), measure_colors=('rgb(31, 119, 180)', 'rgb(176, 196, 221)'), horizontal_spacing=None, vertical_spacing=None, scatter_options={}, **layout_options)¶ deprecated, use instead the plotly.graph_objects trace
plotly.graph_objects.Indicator
.- Parameters
| list | tuple) data ((pd.DataFrame) – either a list/tuple of dictionaries or a pandas DataFrame.
markers ((str)) – the column name or dictionary key for the markers in each subplot.
measures ((str)) – the column name or dictionary key for the measure bars in each subplot. This bar usually represents the quantitative measure of performance, usually a list of two values [a, b] and are the blue bars in the foreground of each subplot by default.
ranges ((str)) – the column name or dictionary key for the qualitative ranges of performance, usually a 3-item list [bad, okay, good]. They correspond to the grey bars in the background of each chart.
subtitles ((str)) – the column name or dictionary key for the subtitle of each subplot chart. The subplots are displayed right underneath each title.
titles ((str)) – the column name or dictionary key for the main label of each subplot chart.
orientation ((bool)) – if ‘h’, the bars are placed horizontally as rows. If ‘v’ the bars are placed vertically in the chart.
range_colors ((list)) – a tuple of two colors between which all the rectangles for the range are drawn. These rectangles are meant to be qualitative indicators against which the marker and measure bars are compared. Default=(‘rgb(200, 200, 200)’, ‘rgb(245, 245, 245)’)
measure_colors ((list)) – a tuple of two colors which is used to color the thin quantitative bars in the bullet chart. Default=(‘rgb(31, 119, 180)’, ‘rgb(176, 196, 221)’)
horizontal_spacing ((float)) – see the ‘horizontal_spacing’ param in plotly.tools.make_subplots. Ranges between 0 and 1.
vertical_spacing ((float)) – see the ‘vertical_spacing’ param in plotly.tools.make_subplots. Ranges between 0 and 1.
scatter_options ((dict)) – describes attributes for the scatter trace in each subplot such as name and marker size. Call help(plotly.graph_objects.Scatter) for more information on valid params.
layout_options – describes attributes for the layout of the figure such as title, height and width. Call help(plotly.graph_objects.Layout) for more information on valid params.
Example 1: Use a Dictionary
>>> 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.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) >>> fig.show()
-
plotly.figure_factory.
create_candlestick
(open, high, low, close, dates=None, direction='both', **kwargs)¶ deprecated, use instead the plotly.graph_objects trace
plotly.graph_objects.Candlestick
- Parameters
open ((list)) – opening values
high ((list)) – high values
low ((list)) – low values
close ((list)) – closing values
dates ((list)) – list of datetime objects. Default: None
direction ((string)) – 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’
kwargs – kwargs passed through plotly.graph_objects.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_objects.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_objects 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']) >>> 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()
-
plotly.figure_factory.
create_choropleth
(fips, values, scope=['usa'], binning_endpoints=None, colorscale=None, order=None, simplify_county=0.02, simplify_state=0.02, asp=None, show_hover=True, show_state_data=True, state_outline=None, county_outline=None, centroid_marker=None, round_legend_values=False, exponent_format=False, legend_title='', **layout_options)¶ deprecated, use instead
plotly.express.choropleth()
with custom GeoJSON.This function also requires
shapely
,geopandas
andplotly-geo
to be installed.Returns figure for county choropleth. Uses data from package_data.
- Parameters
fips ((list)) – list of FIPS values which correspond to the con catination of state and county ids. An example is ‘01001’.
values ((list)) – list of numbers/strings which correspond to the fips list. These are the values that will determine how the counties are colored.
scope ((list)) – list of states and/or states abbreviations. Fits all states in the camera tightly. Selecting [‘usa’] is the equivalent of appending all 50 states into your scope list. Selecting only ‘usa’ does not include ‘Alaska’, ‘Puerto Rico’, ‘American Samoa’, ‘Commonwealth of the Northern Mariana Islands’, ‘Guam’, ‘United States Virgin Islands’. These must be added manually to the list. Default = [‘usa’]
binning_endpoints ((list)) – ascending numbers which implicitly define real number intervals which are used as bins. The colorscale used must have the same number of colors as the number of bins and this will result in a categorical colormap.
colorscale ((list)) –
a list of colors with length equal to the number of categories of colors. The length must match either all unique numbers in the ‘values’ list or if endpoints is being used, the number of categories created by the endpoints.
For example, if binning_endpoints = [4, 6, 8], then there are 4 bins: [-inf, 4), [4, 6), [6, 8), [8, inf)
order ((list)) – a list of the unique categories (numbers/bins) in any desired order. This is helpful if you want to order string values to a chosen colorscale.
simplify_county ((float)) – determines the simplification factor for the counties. The larger the number, the fewer vertices and edges each polygon has. See http://toblerity.org/shapely/manual.html#object.simplify for more information. Default = 0.02
simplify_state ((float)) – simplifies the state outline polygon. See http://toblerity.org/shapely/manual.html#object.simplify for more information. Default = 0.02
asp ((float)) – the width-to-height aspect ratio for the camera. Default = 2.5
show_hover ((bool)) – show county hover and centroid info
show_state_data ((bool)) – reveals state boundary lines
state_outline ((dict)) – dict of attributes of the state outline including width and color. See https://plot.ly/python/reference/#scatter-marker-line for all valid params
county_outline ((dict)) – dict of attributes of the county outline including width and color. See https://plot.ly/python/reference/#scatter-marker-line for all valid params
centroid_marker ((dict)) – dict of attributes of the centroid marker. The centroid markers are invisible by default and appear visible on selection. See https://plot.ly/python/reference/#scatter-marker for all valid params
round_legend_values ((bool)) – automatically round the numbers that appear in the legend to the nearest integer. Default = False
exponent_format ((bool)) – if set to True, puts numbers in the K, M, B number format. For example 4000.0 becomes 4.0K Default = False
legend_title ((str)) – title that appears above the legend
**layout_options –
a **kwargs argument for all layout parameters
Example 1: Florida:
import plotly.plotly as py import plotly.figure_factory as ff import numpy as np import pandas as pd df_sample = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv' ) df_sample_r = df_sample[df_sample['STNAME'] == 'Florida'] values = df_sample_r['TOT_POP'].tolist() fips = df_sample_r['FIPS'].tolist() binning_endpoints = list(np.mgrid[min(values):max(values):4j]) colorscale = ["#030512","#1d1d3b","#323268","#3d4b94","#3e6ab0", "#4989bc","#60a7c7","#85c5d3","#b7e0e4","#eafcfd"] fig = ff.create_choropleth( fips=fips, values=values, scope=['Florida'], show_state_data=True, colorscale=colorscale, binning_endpoints=binning_endpoints, round_legend_values=True, plot_bgcolor='rgb(229,229,229)', paper_bgcolor='rgb(229,229,229)', legend_title='Florida Population', county_outline={'color': 'rgb(255,255,255)', 'width': 0.5}, exponent_format=True, )
Example 2: New England:
import plotly.figure_factory as ff import pandas as pd NE_states = ['Connecticut', 'Maine', 'Massachusetts', 'New Hampshire', 'Rhode Island'] df_sample = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv' ) df_sample_r = df_sample[df_sample['STNAME'].isin(NE_states)] colorscale = ['rgb(68.0, 1.0, 84.0)', 'rgb(66.0, 64.0, 134.0)', 'rgb(38.0, 130.0, 142.0)', 'rgb(63.0, 188.0, 115.0)', 'rgb(216.0, 226.0, 25.0)'] values = df_sample_r['TOT_POP'].tolist() fips = df_sample_r['FIPS'].tolist() fig = ff.create_choropleth( fips=fips, values=values, scope=NE_states, show_state_data=True ) fig.show()
Example 3: California and Surrounding States:
import plotly.figure_factory as ff import pandas as pd df_sample = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/minoritymajority.csv' ) df_sample_r = df_sample[df_sample['STNAME'] == 'California'] values = df_sample_r['TOT_POP'].tolist() fips = df_sample_r['FIPS'].tolist() colorscale = [ 'rgb(193, 193, 193)', 'rgb(239,239,239)', 'rgb(195, 196, 222)', 'rgb(144,148,194)', 'rgb(101,104,168)', 'rgb(65, 53, 132)' ] fig = ff.create_choropleth( fips=fips, values=values, colorscale=colorscale, scope=['CA', 'AZ', 'Nevada', 'Oregon', ' Idaho'], binning_endpoints=[14348, 63983, 134827, 426762, 2081313], county_outline={'color': 'rgb(255,255,255)', 'width': 0.5}, legend_title='California Counties', title='California and Nearby States' ) fig.show()
Example 4: USA:
import plotly.figure_factory as ff import numpy as np import pandas as pd df_sample = pd.read_csv( 'https://raw.githubusercontent.com/plotly/datasets/master/laucnty16.csv' ) df_sample['State FIPS Code'] = df_sample['State FIPS Code'].apply( lambda x: str(x).zfill(2) ) df_sample['County FIPS Code'] = df_sample['County FIPS Code'].apply( lambda x: str(x).zfill(3) ) df_sample['FIPS'] = ( df_sample['State FIPS Code'] + df_sample['County FIPS Code'] ) binning_endpoints = list(np.linspace(1, 12, len(colorscale) - 1)) colorscale = ["#f7fbff", "#ebf3fb", "#deebf7", "#d2e3f3", "#c6dbef", "#b3d2e9", "#9ecae1", "#85bcdb", "#6baed6", "#57a0ce", "#4292c6", "#3082be", "#2171b5", "#1361a9", "#08519c", "#0b4083","#08306b"] fips = df_sample['FIPS'] values = df_sample['Unemployment Rate (%)'] fig = ff.create_choropleth( fips=fips, values=values, scope=['usa'], binning_endpoints=binning_endpoints, colorscale=colorscale, show_hover=True, centroid_marker={'opacity': 0}, asp=2.9, title='USA by Unemployment %', legend_title='Unemployment %' ) fig.show()
-
plotly.figure_factory.
create_dendrogram
(X, orientation='bottom', labels=None, colorscale=None, distfun=None, linkagefun=<function <lambda>>, hovertext=None, color_threshold=None)¶ Function that returns a dendrogram Plotly figure object. This is a thin wrapper around scipy.cluster.hierarchy.dendrogram.
See also https://dash.plot.ly/dash-bio/clustergram.
- Parameters
X ((ndarray)) – Matrix of observations as array of arrays
orientation ((str)) – ‘top’, ‘right’, ‘bottom’, or ‘left’
labels ((list)) – List of axis category labels(observation labels)
colorscale ((list)) – Optional colorscale for the dendrogram tree. Requires 8 colors to be specified, the 7th of which is ignored. With scipy>=1.5.0, the 2nd, 3rd and 6th are used twice as often as the others. Given a shorter list, the missing values are replaced with defaults and with a longer list the extra values are ignored.
distfun ((function)) – Function to compute the pairwise distance from the observations
linkagefun ((function)) – Function to compute the linkage matrix from the pairwise distances
hovertext ((list[list])) – List of hovertext for constituent traces of dendrogram clusters
color_threshold ((double)) – Value at which the separation of clusters will be made
Example 1: Simple bottom oriented dendrogram
>>> from plotly.figure_factory import create_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
>>> from plotly.figure_factory import create_dendrogram
>>> 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.update_layout({'width':700, 'height':500}) >>> dendro.show()
Example 3: Dendrogram with Pandas
>>> 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()
-
plotly.figure_factory.
create_distplot
(hist_data, group_labels, bin_size=1.0, curve_type='kde', colors=None, rug_text=None, histnorm='probability density', show_hist=True, show_curve=True, show_rug=True)¶ Function that creates a distplot similar to seaborn.distplot; this function is deprecated, use instead
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.
- Parameters
hist_data ((list[list])) – Use list of lists to plot multiple data sets on the same plot.
bin_size ((list[float]|float)) – Size of histogram bins. Default = 1.
curve_type ((str)) – ‘kde’ or ‘normal’. Default = ‘kde’
histnorm ((str)) – ‘probability density’ or ‘probability’ Default = ‘probability density’
show_hist ((bool)) – Add histogram to distplot? Default = True
show_curve ((bool)) – Add curve to distplot? Default = True
show_rug ((bool)) – Add rug to distplot? Default = True
- 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') >>> 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()
-
plotly.figure_factory.
create_facet_grid
(df, x=None, y=None, facet_row=None, facet_col=None, color_name=None, colormap=None, color_is_cat=False, facet_row_labels=None, facet_col_labels=None, height=None, width=None, trace_type='scatter', scales='fixed', dtick_x=None, dtick_y=None, show_boxes=True, ggplot2=False, binsize=1, **kwargs)¶ Returns figure for facet grid; this function is deprecated, since plotly.express functions should be used instead, for example
>>> import plotly.express as px >>> tips = px.data.tips() >>> fig = px.scatter(tips, ... x='total_bill', ... y='tip', ... facet_row='sex', ... facet_col='smoker', ... color='size')
- Parameters
df ((pd.DataFrame)) – the dataframe of columns for the facet grid.
x ((str)) – the name of the dataframe column for the x axis data.
y ((str)) – the name of the dataframe column for the y axis data.
facet_row ((str)) – the name of the dataframe column that is used to facet the grid into row panels.
facet_col ((str)) – the name of the dataframe column that is used to facet the grid into column panels.
color_name ((str)) – the name of your dataframe column that will function as the colormap variable.
colormap ((str|list|dict)) – the param that determines how the color_name column colors the data. If the dataframe contains numeric data, then a dictionary of colors will group the data categorically while a Plotly Colorscale name or a custom colorscale will treat it numerically. To learn more about colors and types of colormap, run
help(plotly.colors)
.color_is_cat ((bool)) –
determines whether a numerical column for the colormap will be treated as categorical (True) or sequential (False).
Default = False.
facet_row_labels ((str|dict)) – set to either ‘name’ or a dictionary of all the unique values in the faceting row mapped to some text to show up in the label annotations. If None, labeling works like usual.
facet_col_labels ((str|dict)) – set to either ‘name’ or a dictionary of all the values in the faceting row mapped to some text to show up in the label annotations. If None, labeling works like usual.
height ((int)) – the height of the facet grid figure.
width ((int)) – the width of the facet grid figure.
trace_type ((str)) – decides the type of plot to appear in the facet grid. The options are ‘scatter’, ‘scattergl’, ‘histogram’, ‘bar’, and ‘box’. Default = ‘scatter’.
scales ((str)) – determines if axes have fixed ranges or not. Valid settings are ‘fixed’ (all axes fixed), ‘free_x’ (x axis free only), ‘free_y’ (y axis free only) or ‘free’ (both axes free).
dtick_x ((float)) – determines the distance between each tick on the x-axis. Default is None which means dtick_x is set automatically.
dtick_y ((float)) – determines the distance between each tick on the y-axis. Default is None which means dtick_y is set automatically.
show_boxes ((bool)) – draws grey boxes behind the facet titles.
ggplot2 ((bool)) – draws the facet grid in the style of
ggplot2
. See http://ggplot2.tidyverse.org/reference/facet_grid.html for reference. Default = Falsebinsize ((int)) – groups all data into bins of a given length.
kwargs ((dict)) – a dictionary of scatterplot arguments.
Examples 1: One Way Faceting
>>> 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( ... mpg, ... x='displ', ... y='cty', ... facet_col='cyl', ... ) >>> fig.show()
Example 2: Two Way Faceting
>>> 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( ... mpg, ... x='displ', ... y='cty', ... facet_row='drv', ... facet_col='cyl', ... ) >>> fig.show()
Example 3: Categorical Coloring
>>> import plotly.figure_factory as ff >>> import pandas as pd >>> mtcars = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/mtcars.csv') >>> mtcars.cyl = mtcars.cyl.astype(str) >>> fig = ff.create_facet_grid( ... mtcars, ... x='mpg', ... y='wt', ... facet_col='cyl', ... color_name='cyl', ... color_is_cat=True, ... ) >>> fig.show()
-
plotly.figure_factory.
create_gantt
(df, colors=None, index_col=None, show_colorbar=False, reverse_colors=False, title='Gantt Chart', bar_width=0.2, showgrid_x=False, showgrid_y=False, height=600, width=None, tasks=None, task_names=None, data=None, group_tasks=False, show_hover_fill=True)¶ deprecated, use instead
plotly.express.timeline()
.Returns figure for a gantt chart
- Parameters
df ((array|list)) – input data for gantt chart. Must be either a a dataframe or a list. If dataframe, the columns must include ‘Task’, ‘Start’ and ‘Finish’. Other columns can be included and used for indexing. If a list, its elements must be dictionaries with the same required column headers: ‘Task’, ‘Start’ and ‘Finish’.
colors ((str|list|dict|tuple)) – either a plotly scale name, an rgb or hex color, a color tuple or a list of colors. An rgb color is of the form ‘rgb(x, y, z)’ where x, y, z belong to the interval [0, 255] and a color tuple is a tuple of the form (a, b, c) where a, b and c belong to [0, 1]. If colors is a list, it must contain the valid color types aforementioned as its members. If a dictionary, all values of the indexing column must be keys in colors.
index_col ((str|float)) – the column header (if df is a data frame) that will function as the indexing column. If df is a list, index_col must be one of the keys in all the items of df.
show_colorbar ((bool)) – determines if colorbar will be visible. Only applies if values in the index column are numeric.
show_hover_fill ((bool)) – enables/disables the hovertext for the filled area of the chart.
reverse_colors ((bool)) – reverses the order of selected colors
title ((str)) – the title of the chart
bar_width ((float)) – the width of the horizontal bars in the plot
showgrid_x ((bool)) – show/hide the x-axis grid
showgrid_y ((bool)) – show/hide the y-axis grid
height ((float)) – the height of the chart
width ((float)) – the width of the chart
Example 1: Simple Gantt Chart
>>> 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')]
>>> # Create a figure >>> fig = create_gantt(df) >>> fig.show()
Example 2: Index by Column with Numerical Entries
>>> 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
>>> 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
>>> 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
>>> 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()
-
plotly.figure_factory.
create_hexbin_mapbox
(data_frame=None, lat=None, lon=None, color=None, nx_hexagon=5, agg_func=None, animation_frame=None, color_discrete_sequence=None, color_discrete_map={}, labels={}, color_continuous_scale=None, range_color=None, color_continuous_midpoint=None, opacity=None, zoom=None, center=None, mapbox_style=None, title=None, template=None, width=None, height=None, min_count=None, show_original_data=False, original_data_marker=None)¶ Returns a figure aggregating scattered points into connected hexagons
- Parameters
data_frame (DataFrame or array-like or dict) – This argument needs to be passed for column names (and not keyword names) to be used. Array-like and dict are transformed internally to a pandas DataFrame. Optional: if missing, a DataFrame gets constructed under the hood using the other arguments.
lat (str or int or Series or array-like) – Either a name of a column in
data_frame
, or a pandas Series or array_like object. Values from this column or array_like are used to position marks according to latitude on a map.lon (str or int or Series or array-like) – Either a name of a column in
data_frame
, or a pandas Series or array_like object. Values from this column or array_like are used to position marks according to longitude on a map.color (str or int or Series or array-like) – Either a name of a column in
data_frame
, or a pandas Series or array_like object. Values from this column or array_like are used to assign color to marks.nx_hexagon (int) – Number of hexagons (horizontally) to be created
agg_func (function) – Numpy array aggregator, it must take as input a 1D array and output a scalar value.
animation_frame (str or int or Series or array-like) – Either a name of a column in
data_frame
, or a pandas Series or array_like object. Values from this column or array_like are used to assign marks to animation frames.color_discrete_sequence (list of str) – Strings should define valid CSS-colors. When
color
is set and the values in the corresponding column are not numeric, values in that column are assigned colors by cycling throughcolor_discrete_sequence
in the order described incategory_orders
, unless the value ofcolor
is a key incolor_discrete_map
. Various useful color sequences are available in theplotly.express.colors
submodules, specificallyplotly.express.colors.qualitative
.color_discrete_map (dict with str keys and str values (default
{}
)) – String values should define valid CSS-colors Used to overridecolor_discrete_sequence
to assign a specific colors to marks corresponding with specific values. Keys incolor_discrete_map
should be values in the column denoted bycolor
. Alternatively, if the values ofcolor
are valid colors, the string'identity'
may be passed to cause them to be used directly.labels (dict with str keys and str values (default
{}
)) – By default, column names are used in the figure for axis titles, legend entries and hovers. This parameter allows this to be overridden. The keys of this dict should correspond to column names, and the values should correspond to the desired label to be displayed.color_continuous_scale (list of str) – Strings should define valid CSS-colors This list is used to build a continuous color scale when the column denoted by
color
contains numeric data. Various useful color scales are available in theplotly.express.colors
submodules, specificallyplotly.express.colors.sequential
,plotly.express.colors.diverging
andplotly.express.colors.cyclical
.range_color (list of two numbers) – If provided, overrides auto-scaling on the continuous color scale.
color_continuous_midpoint (number (default
None
)) – If set, computes the bounds of the continuous color scale to have the desired midpoint. Setting this value is recommended when usingplotly.express.colors.diverging
color scales as the inputs tocolor_continuous_scale
.opacity (float) – Value between 0 and 1. Sets the opacity for markers.
zoom (int (default
8
)) – Between 0 and 20. Sets map zoom level.center (dict) – Dict keys are
'lat'
and'lon'
Sets the center point of the map.mapbox_style (str (default
'basic'
, needs Mapbox API token)) – Identifier of base map style, some of which require a Mapbox or Stadia Maps API token to be set usingplotly.express.set_mapbox_access_token()
. Allowed values which do not require a token are'open-street-map'
,'white-bg'
,'carto- positron'
,'carto-darkmatter'
. Allowed values which require a Mapbox API token are'basic'
,'streets'
,'outdoors'
,'light'
,'dark'
,'satellite'
,'satellite-streets'
. Allowed values which require a Stadia Maps API token are'stamen-terrain'
,'stamen- toner'
,'stamen-watercolor'
.title (str) – The figure title.
template (str or dict or plotly.graph_objects.layout.Template instance) – The figure template name (must be a key in plotly.io.templates) or definition.
width (int (default
None
)) – The figure width in pixels.height (int (default
None
)) – The figure height in pixels.min_count (int) – Minimum number of points in a hexagon for it to be displayed. If None and color is not set, display all hexagons. If None and color is set, only display hexagons that contain points.
show_original_data (bool) – Whether to show the original data on top of the hexbin aggregation.
original_data_marker (dict) – Scattermapbox marker options.
- Returns
- Return type
-
plotly.figure_factory.
create_ohlc
(open, high, low, close, dates=None, direction='both', **kwargs)¶ deprecated, use instead the plotly.graph_objects trace
plotly.graph_objects.Ohlc
- Parameters
open ((list)) – opening values
high ((list)) – high values
low ((list)) – low values
close ((list)) – closing
dates ((list)) – list of datetime objects. Default: None
direction ((string)) – 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’
kwargs – kwargs passed through plotly.graph_objects.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_objects.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()
-
plotly.figure_factory.
create_quiver
(x, y, u, v, scale=0.1, arrow_scale=0.3, angle=0.3490658503988659, scaleratio=None, **kwargs)¶ Returns data for a quiver plot.
- Parameters
x ((list|ndarray)) – x coordinates of the arrow locations
y ((list|ndarray)) – y coordinates of the arrow locations
u ((list|ndarray)) – x components of the arrow vectors
v ((list|ndarray)) – y components of the arrow vectors
in [0,1]) scale ((float) – scales size of the arrows(ideally to avoid overlap). Default = .1
in [0,1]) arrow_scale ((float) – value multiplied to length of barb to get length of arrowhead. Default = .3
in radians) angle ((angle) – angle of arrowhead. Default = pi/9
float) scaleratio ((positive) – 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.
kwargs – kwargs passed through plotly.graph_objects.Scatter for more information on valid kwargs call help(plotly.graph_objects.Scatter)
- Rtype (dict)
returns a representation of quiver figure.
Example 1: Trivial Quiver
>>> 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) >>> fig.show()
Example 2: Quiver plot using meshgrid
>>> 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) >>> fig.show()
Example 3: Styling the quiver plot
>>> 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.update_layout(title='Quiver Plot') >>> fig.show()
Example 4: Forcing a fix scale ratio to maintain the arrow length
>>> 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()
-
plotly.figure_factory.
create_scatterplotmatrix
(df, index=None, endpts=None, diag='scatter', height=500, width=500, size=6, title='Scatterplot Matrix', colormap=None, colormap_type='cat', dataframe=None, headers=None, index_vals=None, **kwargs)¶ Returns data for a scatterplot matrix; deprecated, use instead the plotly.graph_objects trace
plotly.graph_objects.Splom
.- Parameters
df ((array)) – array of the data with column headers
index ((str)) – name of the index column in data array
endpts ((list|tuple)) – takes an increasing sequece of numbers that defines intervals on the real line. They are used to group the entries in an index of numbers into their corresponding interval and therefore can be treated as categorical data
diag ((str)) – sets the chart type for the main diagonal plots. The options are ‘scatter’, ‘histogram’ and ‘box’.
height ((int|float)) – sets the height of the chart
width ((int|float)) – sets the width of the chart
size ((float)) – sets the marker size (in px)
title ((str)) – the title label of the scatterplot matrix
colormap ((str|tuple|list|dict)) – either a plotly scale name, an rgb or hex color, a color tuple, a list of colors or a dictionary. An rgb color is of the form ‘rgb(x, y, z)’ where x, y and z belong to the interval [0, 255] and a color tuple is a tuple of the form (a, b, c) where a, b and c belong to [0, 1]. If colormap is a list, it must contain valid color types as its members. If colormap is a dictionary, all the string entries in the index column must be a key in colormap. In this case, the colormap_type is forced to ‘cat’ or categorical
colormap_type ((str)) – determines how colormap is interpreted. Valid choices are ‘seq’ (sequential) and ‘cat’ (categorical). If ‘seq’ is selected, only the first two colors in colormap will be considered (when colormap is a list) and the index values will be linearly interpolated between those two colors. This option is forced if all index values are numeric. If ‘cat’ is selected, a color from colormap will be assigned to each category from index, including the intervals if endpts is being used
**kwargs ((dict)) –
a dictionary of scatterplot arguments The only forbidden parameters are ‘size’, ‘color’ and ‘colorscale’ in ‘marker’
Example 1: Vanilla Scatterplot Matrix
>>> from plotly.graph_objects import graph_objects >>> from plotly.figure_factory import create_scatterplotmatrix
>>> import numpy as np >>> import pandas as pd
>>> # Create dataframe >>> df = pd.DataFrame(np.random.randn(10, 2), ... columns=['Column 1', 'Column 2'])
>>> # Create scatterplot matrix >>> fig = create_scatterplotmatrix(df) >>> fig.show()
Example 2: Indexing a Column
>>> from plotly.graph_objects import graph_objects >>> 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'])
>>> # 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) >>> fig.show()
Example 3: Styling the Diagonal Subplots
>>> from plotly.graph_objects import graph_objects >>> 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'])
>>> # 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) >>> fig.show()
Example 4: Use a Theme to Style the Subplots
>>> from plotly.graph_objects import graph_objects >>> 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 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()
Example 5: Example 4 with Interval Factoring
>>> from plotly.graph_objects import graph_objects >>> 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
>>> from plotly.graph_objects import graph_objects >>> 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()
-
plotly.figure_factory.
create_streamline
(x, y, u, v, density=1, angle=0.3490658503988659, arrow_scale=0.09, **kwargs)¶ Returns data for a streamline plot.
- Parameters
x ((list|ndarray)) – 1 dimensional, evenly spaced list or array
y ((list|ndarray)) – 1 dimensional, evenly spaced list or array
u ((ndarray)) – 2 dimensional array
v ((ndarray)) – 2 dimensional array
density ((float|int)) – 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
in radians) angle ((angle) – angle of arrowhead. Default = pi/9
in [0,1]) arrow_scale ((float) – value to scale length of arrowhead Default = .09
kwargs – kwargs passed through plotly.graph_objects.Scatter for more information on valid kwargs call help(plotly.graph_objects.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) >>> fig.show()
-
plotly.figure_factory.
create_table
(table_text, colorscale=None, font_colors=None, index=False, index_title='', annotation_offset=0.45, height_constant=30, hoverinfo='none', **kwargs)¶ Function that creates data tables.
See also the plotly.graph_objects trace
plotly.graph_objects.Table
- Parameters
| list[list]) text ((pandas.Dataframe) – data for table.
colorscale ((str|list[list])) – Colorscale for table where the color at value 0 is the header color, .5 is the first table color and 1 is the second table color. (Set .5 and 1 to avoid the striped table effect). Default=[[0, ‘#66b2ff’], [.5, ‘#d9d9d9’], [1, ‘#ffffff’]]
font_colors ((list)) – Color for fonts in table. Can be a single color, three colors, or a color for each row in the table. Default=[‘#000000’] (black text for the entire table)
height_constant ((int)) – Constant multiplied by # of rows to create table height. Default=30.
index ((bool)) – Create (header-colored) index column index from Pandas dataframe or list[0] for each list in text. Default=False.
index_title ((string)) – Title for index column. Default=’’.
kwargs – kwargs passed through plotly.graph_objects.Heatmap. These kwargs describe other attributes about the annotated Heatmap trace such as the colorscale. For more information on valid kwargs call help(plotly.graph_objects.Heatmap)
Example 1: Simple Plotly 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) >>> table.show()
Example 2: Table with Custom Coloring
>>> 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
>>> 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=' ') >>> df_p = df[0:25] >>> table_simple = create_table(df_p) >>> table_simple.show()
-
plotly.figure_factory.
create_ternary_contour
(coordinates, values, pole_labels=['a', 'b', 'c'], width=500, height=500, ncontours=None, showscale=False, coloring=None, colorscale='Bluered', linecolor=None, title=None, interp_mode='ilr', showmarkers=False)¶ Ternary contour plot.
- Parameters
coordinates (list or ndarray) – Barycentric coordinates of shape (2, N) or (3, N) where N is the number of data points. The sum of the 3 coordinates is expected to be 1 for all data points.
values (array-like) – Data points of field to be represented as contours.
pole_labels (str, default ['a', 'b', 'c']) – Names of the three poles of the triangle.
width (int) – Figure width.
height (int) – Figure height.
ncontours (int or None) – Number of contours to display (determined automatically if None).
showscale (bool, default False) – If True, a colorbar showing the color scale is displayed.
coloring (None or 'lines') – How to display contour. Filled contours if None, lines if
lines
.colorscale (None or str (Plotly colormap)) – colorscale of the contours.
linecolor (None or rgb color) – Color used for lines.
colorscale
has to be set to None, otherwise line colors are determined fromcolorscale
.interp_mode ('ilr' (default) or 'cartesian') – Defines how data are interpolated to compute contours. If ‘irl’, ILR (Isometric Log-Ratio) of compositional data is performed. If ‘cartesian’, contours are determined in Cartesian space.
showmarkers (bool, default False) – If True, markers corresponding to input compositional points are superimposed on contours, using the same colorscale.
Examples
Example 1: ternary contour plot with filled contours
>>> 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_ternary_contour(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_ternary_contour(np.stack((a, b)), z)
Example 2: ternary contour plot with line contours
>>> fig = ff.create_ternary_contour(np.stack((a, b, c)), z, coloring='lines')
Example 3: customize number of contours
>>> fig = ff.create_ternary_contour(np.stack((a, b, c)), z, ncontours=8)
Example 4: superimpose contour plot and original data as markers
>>> fig = ff.create_ternary_contour(np.stack((a, b, c)), z, coloring='lines', ... showmarkers=True)
Example 5: customize title and pole labels
>>> fig = ff.create_ternary_contour(np.stack((a, b, c)), z, ... title='Ternary plot', ... pole_labels=['clay', 'quartz', 'fledspar'])
-
plotly.figure_factory.
create_trisurf
(x, y, z, simplices, colormap=None, show_colorbar=True, scale=None, color_func=None, title='Trisurf Plot', plot_edges=True, showbackground=True, backgroundcolor='rgb(230, 230, 230)', gridcolor='rgb(255, 255, 255)', zerolinecolor='rgb(255, 255, 255)', edges_color='rgb(50, 50, 50)', height=800, width=800, aspectratio=None)¶ Returns figure for a triangulated surface plot
- Parameters
x ((array)) – data values of x in a 1D array
y ((array)) – data values of y in a 1D array
z ((array)) – data values of z in a 1D array
simplices ((array)) – an array of shape (ntri, 3) where ntri is the number of triangles in the triangularization. Each row of the array contains the indicies of the verticies of each triangle
colormap ((str|tuple|list)) – either a plotly scale name, an rgb or hex color, a color tuple or a list of colors. An rgb color is of the form ‘rgb(x, y, z)’ where x, y, z belong to the interval [0, 255] and a color tuple is a tuple of the form (a, b, c) where a, b and c belong to [0, 1]. If colormap is a list, it must contain the valid color types aforementioned as its members
show_colorbar ((bool)) – determines if colorbar is visible
scale ((list|array)) – sets the scale values to be used if a non- linearly interpolated colormap is desired. If left as None, a linear interpolation between the colors will be excecuted
color_func ((function|list)) – The parameter that determines the coloring of the surface. Takes either a function with 3 arguments x, y, z or a list/array of color values the same length as simplices. If None, coloring will only depend on the z axis
title ((str)) – title of the plot
plot_edges ((bool)) – determines if the triangles on the trisurf are visible
showbackground ((bool)) – makes background in plot visible
backgroundcolor ((str)) – color of background. Takes a string of the form ‘rgb(x,y,z)’ x,y,z are between 0 and 255 inclusive
gridcolor ((str)) – color of the gridlines besides the axes. Takes a string of the form ‘rgb(x,y,z)’ x,y,z are between 0 and 255 inclusive
zerolinecolor ((str)) – color of the axes. Takes a string of the form ‘rgb(x,y,z)’ x,y,z are between 0 and 255 inclusive
edges_color ((str)) – color of the edges, if plot_edges is True
height ((int|float)) – the height of the plot (in pixels)
width ((int|float)) – the width of the plot (in pixels)
aspectratio ((dict)) – a dictionary of the aspect ratio values for 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
>>> from plotly.figure_factory import create_trisurf >>> from plotly.graph_objects import graph_objects
>>> # 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
>>> from plotly.figure_factory import create_trisurf >>> from plotly.graph_objects import graph_objects
>>> # 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
>>> from plotly.figure_factory import create_trisurf >>> from plotly.graph_objects import graph_objects
>>> # 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
>>> from plotly.figure_factory import create_trisurf >>> from plotly.graph_objects import graph_objects
>>> # 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
>>> from plotly.figure_factory import create_trisurf >>> from plotly.graph_objects import graph_objects
>>> # 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' ... )
-
plotly.figure_factory.
create_violin
(data, data_header=None, group_header=None, colors=None, use_colorscale=False, group_stats=None, rugplot=True, sort=False, height=450, width=600, title='Violin and Rug Plot')¶ deprecated, use instead the plotly.graph_objects trace
plotly.graph_objects.Violin
.- Parameters
data ((list|array)) – accepts either a list of numerical values, a list of dictionaries all with identical keys and at least one column of numeric values, or a pandas dataframe with at least one column of numbers.
data_header ((str)) – the header of the data column to be used from an inputted pandas dataframe. Not applicable if ‘data’ is a list of numeric values.
group_header ((str)) – applicable if grouping data by a variable. ‘group_header’ must be set to the name of the grouping variable.
colors ((str|tuple|list|dict)) – either a plotly scale name, an rgb or hex color, a color tuple, a list of colors or a dictionary. An rgb color is of the form ‘rgb(x, y, z)’ where x, y and z belong to the interval [0, 255] and a color tuple is a tuple of the form (a, b, c) where a, b and c belong to [0, 1]. If colors is a list, it must contain valid color types as its members.
use_colorscale ((bool)) – only applicable if grouping by another variable. Will implement a colorscale based on the first 2 colors of param colors. This means colors must be a list with at least 2 colors in it (Plotly colorscales are accepted since they map to a list of two rgb colors). Default = False
group_stats ((dict)) – a dictionary where each key is a unique value from the group_header column in data. Each value must be a number and will be used to color the violin plots if a colorscale is being used.
rugplot ((bool)) – determines if a rugplot is draw on violin plot. Default = True
sort ((bool)) – determines if violins are sorted alphabetically (True) or by input order (False). Default = False
height ((float)) – the height of the violin plot.
width ((float)) – the width of the violin plot.
title ((str)) – the title of the violin plot.
Example 1: Single Violin Plot
>>> from plotly.figure_factory import create_violin >>> import plotly.graph_objects as graph_objects
>>> import numpy as np >>> from scipy import stats
>>> # create list of random values >>> data_list = np.random.randn(100)
>>> # create violin fig >>> fig = create_violin(data_list, colors='#604d9e')
>>> # plot >>> fig.show()
Example 2: Multiple Violin Plots with Qualitative Coloring
>>> from plotly.figure_factory import create_violin >>> import plotly.graph_objects 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
>>> from plotly.figure_factory import create_violin >>> import plotly.graph_objects 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()
Submodules¶
plotly.figure_factory.utils module¶
-
plotly.figure_factory.utils.
annotation_dict_for_label
(text, lane, num_of_lanes, subplot_spacing, row_col='col', flipped=True, right_side=True, text_color='#0f0f0f')¶ Returns annotation dict for label of n labels of a 1xn or nx1 subplot.
- Parameters
text ((str)) – the text for a label.
lane ((int)) – the label number for text. From 1 to n inclusive.
num_of_lanes ((int)) – the number ‘n’ of rows or columns in subplot.
subplot_spacing ((float)) – the value for the horizontal_spacing and vertical_spacing params in your plotly.tools.make_subplots() call.
row_col ((str)) – choose whether labels are placed along rows or columns.
flipped ((bool)) – flips text by 90 degrees. Text is printed horizontally if set to True and row_col=’row’, or if False and row_col=’col’.
right_side ((bool)) – only applicable if row_col is set to ‘row’.
text_color ((str)) – color of the text.
-
plotly.figure_factory.utils.
endpts_to_intervals
(endpts)¶ Returns a list of intervals for categorical colormaps
Accepts a list or tuple of sequentially increasing numbers and returns a list representation of the mathematical intervals with these numbers as endpoints. For example, [1, 6] returns [[-inf, 1], [1, 6], [6, inf]]
- Raises
(PlotlyError) If input is not a list or tuple
- Raises
(PlotlyError) If the input contains a string
- Raises
(PlotlyError) If any number does not increase after the previous one in the sequence
-
plotly.figure_factory.utils.
flatten
(array)¶ Uses list comprehension to flatten array
- Parameters
(array) – An iterable to flatten
- Raises
(PlotlyError) – If iterable is not nested.
- Rtype (list)
The flattened list.
-
plotly.figure_factory.utils.
is_sequence
(obj)¶
-
plotly.figure_factory.utils.
list_of_options
(iterable, conj='and', period=True)¶ Returns an English listing of objects seperated by commas ‘,’
For example, [‘foo’, ‘bar’, ‘baz’] becomes ‘foo, bar and baz’ if the conjunction ‘and’ is selected.
-
plotly.figure_factory.utils.
validate_dataframe
(array)¶ Validates all strings or numbers in each dataframe column
- Raises
(PlotlyError) If there are any two items in any list whose types differ
-
plotly.figure_factory.utils.
validate_equal_length
(*args)¶ Validates that data lists or ndarrays are the same length.
- Raises
(PlotlyError) If any data lists are not the same length.
-
plotly.figure_factory.utils.
validate_index
(index_vals)¶ Validates if a list contains all numbers or all strings
- Raises
(PlotlyError) If there are any two items in the list whose types differ
-
plotly.figure_factory.utils.
validate_positive_scalars
(**kwargs)¶ Validates that all values given in key/val pairs are positive.
Accepts kwargs to improve Exception messages.
- Raises
(PlotlyError) If any value is < 0 or raises.