Scatter Plot, Scattergl Plot and Bubble Charts ”; Previous Next This chapter emphasizes on details about Scatter Plot, Scattergl Plot and Bubble Charts. First, let us study about Scatter Plot. Scatter Plot Scatter plots are used to plot data points on a horizontal and a vertical axis to show how one variable affects another. Each row in the data table is represented by a marker whose position depends on its values in the columns set on the X and Y axes. The scatter() method of graph_objs module (go.Scatter) produces a scatter trace. Here, the mode property decides the appearance of data points. Default value of mode is lines which displays a continuous line connecting data points. If set to markers, only the data points represented by small filled circles are displayed. When mode is assigned ‘lines+markers’, both circles and lines are displayed. In the following example, plots scatter traces of three sets of randomly generated points in Cartesian coordinate system. Each trace displayed with different mode property is explained below. import numpy as np N = 100 x_vals = np.linspace(0, 1, N) y1 = np.random.randn(N) + 5 y2 = np.random.randn(N) y3 = np.random.randn(N) – 5 trace0 = go.Scatter( x = x_vals, y = y1, mode = ”markers”, name = ”markers” ) trace1 = go.Scatter( x = x_vals, y = y2, mode = ”lines+markers”, name = ”line+markers” ) trace2 = go.Scatter( x = x_vals, y = y3, mode = ”lines”, name = ”line” ) data = [trace0, trace1, trace2] fig = go.Figure(data = data) iplot(fig) The output of Jupyter notebook cell is as given below − Scattergl Plot WebGL (Web Graphics Library) is a JavaScript API for rendering interactive 2D and 3D graphics within any compatible web browser without the use of plug-ins. WebGL is fully integrated with other web standards, allowing Graphics Processing Unit (GPU) accelerated usage of image processing. Plotly you can implement WebGL with Scattergl() in place of Scatter() for increased speed, improved interactivity, and the ability to plot even more data. The go.scattergl() function which gives better performance when a large number of data points are involved. import numpy as np N = 100000 x = np.random.randn(N) y = np.random.randn(N) trace0 = go.Scattergl( x = x, y = y, mode = ”markers” ) data = [trace0] layout = go.Layout(title = “scattergl plot “) fig = go.Figure(data = data, layout = layout) iplot(fig) The output is mentioned below − Bubble charts A bubble chart displays three dimensions of data. Each entity with its three dimensions of associated data is plotted as a disk (bubble) that expresses two of the dimensions through the disk”s xy location and the third through its size. The sizes of the bubbles are determined by the values in the third data series. Bubble chart is a variation of the scatter plot, in which the data points are replaced with bubbles. If your data has three dimensions as shown below, creating a Bubble chart will be a good choice. Company Products Sale Share A 13 2354 23 B 6 5423 47 C 23 2451 30 Bubble chart is produced with go.Scatter() trace. Two of the above data series are given as x and y properties. Third dimension is shown by marker with its size representing third data series. In the above mentioned case, we use products and sale as x and y properties and market share as marker size. Enter the following code in Jupyter notebook. company = [”A”,”B”,”C”] products = [13,6,23] sale = [2354,5423,4251] share = [23,47,30] fig = go.Figure(data = [go.Scatter( x = products, y = sale, text = [ ”company:”+c+” share:”+str(s)+”%” for c in company for s in share if company.index(c)==share.index(s) ], mode = ”markers”, marker_size = share, marker_color = [”blue”,”red”,”yellow”]) ]) iplot(fig) The output would be as shown below − Print Page Previous Next Advertisements ”;
Category: plotly
Plotly – Exporting to Static Images ”; Previous Next Outputs of offline graphs can be exported to various raster and vector image formats. For that purpose, we need to install two dependencies – orca and psutil. Orca Orca stands for Open-source Report Creator App. It is an Electron app that generates images and reports of plotly graphs, dash apps, dashboards from the command line. Orca is the backbone of Plotly”s Image Server. psutil psutil (python system and process utilities) is a cross-platform library for retrieving information on running processes and system utilization in Python. It implements many functionalities offered by UNIX command line tools such as: ps, top, netstat, ifconfig, who, etc. psutil supports all major operating systems such as Linux, Windows and MacOs Installation of Orca and psutil If you are using Anaconda distribution of Python, installation of orca and psutil is very easily done by conda package manager as follows − conda install -c plotly plotly-orca psutil Since, orca is not available in PyPi repository. You can instead use npm utility to install it. npm install -g [email protected] orca Use pip to install psutil pip install psutil If you are not able to use npm or conda, prebuilt binaries of orca can also be downloaded from the following website which is available at https://github.com/plotly/orca/releases. To export Figure object to png, jpg or WebP format, first, import plotly.io module import plotly.io as pio Now, we can call write_image() function as follows − pio.write_image(fig, ‘sinewave.png’) pio.write_image(fig, ‘sinewave.jpeg’) pio.write_image(fig,’sinewave.webp) The orca tool also supports exporting plotly to svg, pdf and eps formats. Pio.write_image(fig, ‘sinewave.svg’) pio.write_image(fig, ‘sinewave.pdf’) In Jupyter notebook, the image object obtained by pio.to_image() function can be displayed inline as follows − Print Page Previous Next Advertisements ”;
Plotly – Slider Control
Plotly – Slider Control ”; Previous Next Plotly has a convenient Slider that can be used to change the view of data/style of a plot by sliding a knob on the control which is placed at the bottom of rendered plot. Slider control is made up of different properties which are as follows − steps property is required for defining sliding positions of knob over the control. method property is having possible values as restyle | relayout | animate | update | skip, default is restyle. args property sets the arguments values to be passed to the Plotly method set in method on slide. We now deploy a simple slider control on a scatter plot which will vary the frequency of sine wave as the knob slides along the control. The slider is configured to have 50 steps. First add 50 traces of sine wave curve with incrementing frequency, all but 10th trace set to visible. Then, we configure each step with restyle method. For each step, all other step objects have visibility set to false. Finally, update Figure object’s layout by initializing sliders property. # Add traces, one for each slider step for step in np.arange(0, 5, 0.1): fig.add_trace( go.Scatter( visible = False, line = dict(color = “blue”, width = 2), name = “𝜈 = ” + str(step), x = np.arange(0, 10, 0.01), y = np.sin(step * np.arange(0, 10, 0.01)) ) ) fig.data[10].visible=True # Create and add slider steps = [] for i in range(len(fig.data)): step = dict( method = “restyle”, args = [“visible”, [False] * len(fig.data)], ) step[“args”][1][i] = True # Toggle i”th trace to “visible” steps.append(step) sliders = [dict(active = 10, steps = steps)] fig.layout.update(sliders=sliders) iplot(fig) To begin with, 10th sine wave trace will be visible. Try sliding the knob across the horizontal control at the bottom. You will see the frequency changing as shown below. Print Page Previous Next Advertisements ”;
Plotly – Format Axis & Ticks
Plotly – Format Axis and Ticks ”; Previous Next You can configure appearance of each axis by specifying the line width and color. It is also possible to define grid width and grid color. Let us learn about the same in detail in this chapter. Plot with Axis and Tick In the Layout object’s properties, setting showticklabels to true will enable ticks. The tickfont property is a dict object specifying font name, size, color, etc. The tickmode property can have two possible values — linear and array. If it is linear, the position of starting tick is determined by tick0 and step between ticks by dtick properties. If tickmode is set to array, you have to provide list of values and labels as tickval and ticktext properties. The Layout object also has Exponentformat attribute set to ‘e’ will cause tick values to be displayed in scientific notation. You also need to set showexponent property to ‘all’. We now format the Layout object in above example to configure x and y axis by specifying line, grid and title font properties and tick mode, values and font. layout = go.Layout( title = “Sine and cos”, xaxis = dict( title = ”angle”, showgrid = True, zeroline = True, showline = True, showticklabels = True, gridwidth = 1 ), yaxis = dict( showgrid = True, zeroline = True, showline = True, gridcolor = ”#bdbdbd”, gridwidth = 2, zerolinecolor = ”#969696”, zerolinewidth = 2, linecolor = ”#636363”, linewidth = 2, title = ”VALUE”, titlefont = dict( family = ”Arial, sans-serif”, size = 18, color = ”lightgrey” ), showticklabels = True, tickangle = 45, tickfont = dict( family = ”Old Standard TT, serif”, size = 14, color = ”black” ), tickmode = ”linear”, tick0 = 0.0, dtick = 0.25 ) ) Plot with Multiple Axes Sometimes it is useful to have dual x or y axes in a figure; for example, when plotting curves with different units together. Matplotlib supports this with the twinx and twiny functions. In the following example, the plot has dual y axes, one showing exp(x) and other showing log(x) x = np.arange(1,11) y1 = np.exp(x) y2 = np.log(x) trace1 = go.Scatter( x = x, y = y1, name = ”exp” ) trace2 = go.Scatter( x = x, y = y2, name = ”log”, yaxis = ”y2” ) data = [trace1, trace2] layout = go.Layout( title = ”Double Y Axis Example”, yaxis = dict( title = ”exp”,zeroline=True, showline = True ), yaxis2 = dict( title = ”log”, zeroline = True, showline = True, overlaying = ”y”, side = ”right” ) ) fig = go.Figure(data=data, layout=layout) iplot(fig) Here, additional y axis is configured as yaxis2 and appears on right side, having ‘log’ as title. Resultant plot is as follows − Print Page Previous Next Advertisements ”;
Plotly – Package Structure
Plotly – Package Structure ”; Previous Next Plotly Python package has three main modules which are given below − plotly.plotly plotly.graph_objs plotly.tools The plotly.plotly module contains functions that require a response from Plotly”s servers. Functions in this module are interface between your local machine and Plotly. The plotly.graph_objs module is the most important module that contains all of the class definitions for the objects that make up the plots you see. Following graph objects are defined − Figure, Data, ayout, Different graph traces like Scatter, Box, Histogram etc. All graph objects are dictionary- and list-like objects used to generate and/or modify every feature of a Plotly plot. The plotly.tools module contains many helpful functions facilitating and enhancing the Plotly experience. Functions for subplot generation, embedding Plotly plots in IPython notebooks, saving and retrieving your credentials are defined in this module. A plot is represented by Figure object which represents Figure class defined in plotly.graph_objs module. It’s constructor needs following parameters − import plotly.graph_objs as go fig = go.Figure(data, layout, frames) The data parameter is a list object in Python. It is a list of all the traces that you wish to plot. A trace is just the name we give to a collection of data which is to be plotted. A trace object is named according to how you want the data displayed on the plotting surface. Plotly provides number of trace objects such as scatter, bar, pie, heatmap etc. and each is returned by respective functions in graph_objs functions. For example: go.scatter() returns a scatter trace. import numpy as np import math #needed for definition of pi xpoints=np.arange(0, math.pi*2, 0.05) ypoints=np.sin(xpoints) trace0 = go.Scatter( x = xpoints, y = ypoints ) data = [trace0] The layout parameter defines the appearance of the plot, and plot features which are unrelated to the data. So we will be able to change things like the title, axis titles, annotations, legends, spacing, font and even draw shapes on top of your plot. layout = go.Layout(title = “Sine wave”, xaxis = {”title”:”angle”}, yaxis = {”title”:”sine”}) A plot can have plot title as well as axis title. It also may have annotations to indicate other descriptions. Finally, there is a Figure object created by go.Figure() function. It is a dictionary-like object that contains both the data object and the layout object. The figure object is eventually plotted. py.iplot(fig) Print Page Previous Next Advertisements ”;
Plotly – Plotting Inline with Jupyter Notebook ”; Previous Next In this chapter, we will study how to do inline plotting with the Jupyter Notebook. In order to display the plot inside the notebook, you need to initiate plotly’s notebook mode as follows − from plotly.offline import init_notebook_mode init_notebook_mode(connected = True) Keep rest of the script as it is and run the notebook cell by pressing Shift+Enter. Graph will be displayed offline inside the notebook itself. import plotly plotly.tools.set_credentials_file(username = ”lathkar”, api_key = ”************”) from plotly.offline import iplot, init_notebook_mode init_notebook_mode(connected = True) import plotly import plotly.graph_objs as go import numpy as np import math #needed for definition of pi xpoints = np.arange(0, math.pi*2, 0.05) ypoints = np.sin(xpoints) trace0 = go.Scatter( x = xpoints, y = ypoints ) data = [trace0] plotly.offline.iplot({ “data”: data,”layout”: go.Layout(title=”Sine wave”)}) Jupyter notebook output will be as shown below − The plot output shows a tool bar at top right. It contains buttons for download as png, zoom in and out, box and lasso, select and hover. Print Page Previous Next Advertisements ”;
Plotly – Online and Offline Plotting ”; Previous Next The following chapter deals with the settings for the online and offline plotting. Let us first study the settings for online plotting. Settings for online plotting Data and graph of online plot are save in your plot.ly account. Online plots are generated by two methods both of which create a unique url for the plot and save it in your Plotly account. py.plot() − returns the unique url and optionally open the url. py.iplot() − when working in a Jupyter Notebook to display the plot in the notebook. We shall now display simple plot of angle in radians vs. its sine value. First, obtain ndarray object of angles between 0 and 2π using arange() function from numpy library. This ndarray object serves as values on x axis of the graph. Corresponding sine values of angles in x which has to be displayed on y axis are obtained by following statements − import numpy as np import math #needed for definition of pi xpoints = np.arange(0, math.pi*2, 0.05) ypoints = np.sin(xpoints) Next, create a scatter trace using Scatter() function in graph_objs module. trace0 = go.Scatter( x = xpoints, y = ypoints ) data = [trace0] Use above list object as argument to plot() function. py.plot(data, filename = ”Sine wave”, auto_open=True) Save following script as plotly1.py import plotly plotly.tools.set_credentials_file(username=”lathkar”, api_key=”********************”) import plotly.plotly as py import plotly.graph_objs as go import numpy as np import math #needed for definition of pi xpoints = np.arange(0, math.pi*2, 0.05) ypoints = np.sin(xpoints) trace0 = go.Scatter( x = xpoints, y = ypoints ) data = [trace0] py.plot(data, filename = ”Sine wave”, auto_open=True) Execute the above mentioned script from command line. Resultant plot will be displayed in the browser at specified URL as stated below. $ python plotly1.py High five! You successfully sent some data to your account on plotly. View your plot in your browser at https://plot.ly/~lathkar/0 Just above the displayed graph, you will find tabs Plot, Data, Python & Rand Forking history. Currently, Plot tab is selected. The Data tab shows a grid containing x and y data points. From Python & R tab, you can view code corresponding to current plot in Python, R, JSON, Matlab etc. Following snapshot shows Python code for the plot as generated above − Setting for Offline Plotting Plotly allows you to generate graphs offline and save them in local machine. The plotly.offline.plot() function creates a standalone HTML that is saved locally and opened inside your web browser. Use plotly.offline.iplot() when working offline in a Jupyter Notebook to display the plot in the notebook. Note − Plotly”s version 1.9.4+ is needed for offline plotting. Change plot() function statement in the script and run. A HTML file named temp-plot.html will be created locally and opened in web browser. plotly.offline.plot( { “data”: data,”layout”: go.Layout(title = “hello world”)}, auto_open = True) Print Page Previous Next Advertisements ”;
Plotly – Home
Plotly Tutorial PDF Version Quick Guide Resources Job Search Discussion This tutorial is about Canada based technical computing company Plotly which is also known for its URL. Here, you will learn about how to develop data analytics and visualization tools. Moreover, this tutorial describes the features of Plotly’s Python graphing library to make interactive and publication-ready graphs for both online and offline viewing. Audience The tutorial is aptly designed for all those who are passionate about learning online graphing, analytics, and statistics tools. Furthermore, it is for those individuals who have keen interest in understanding how Plotly helps in providing tools for scientific graphing libraries of the computer programming languages such as Python, R, MATLAB, Perl, Julia, Arduino, and REST. Prerequisites To work with Plotly, you need to create an account on the official website. The details about how to create an account and get login is discussed in the tutorial. If you are novice to knowledge about data analytics, visualization tools or any of the programming languages like Python, R, MATLAB, Arduino, REST, Julia and Perl, we suggest you to go through tutorials related to these before proceeding with this tutorial. Print Page Previous Next Advertisements ”;
Plotly – Subplots and Inset Plots ”; Previous Next Here, we will understand the concept of subplots and inset plots in Plotly. Making Subplots Sometimes it is helpful to compare different views of data side by side. This supports the concept of subplots. It offers make_subplots() function in plotly.tools module. The function returns a Figure object. The following statement creates two subplots in one row. fig = tools.make_subplots(rows = 1, cols = 2) We can now add two different traces (the exp and log traces in example above) to the figure. fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) The Layout of figure is further configured by specifying title, width, height, etc. using update() method. fig[”layout”].update(height = 600, width = 800s, title = ”subplots”) Here”s the complete script − from plotly import tools import plotly.plotly as py import plotly.graph_objs as go from plotly.offline import iplot, init_notebook_mode init_notebook_mode(connected = True) import numpy as np x = np.arange(1,11) y1 = np.exp(x) y2 = np.log(x) trace1 = go.Scatter( x = x, y = y1, name = ”exp” ) trace2 = go.Scatter( x = x, y = y2, name = ”log” ) fig = tools.make_subplots(rows = 1, cols = 2) fig.append_trace(trace1, 1, 1) fig.append_trace(trace2, 1, 2) fig[”layout”].update(height = 600, width = 800, title = ”subplot”) iplot(fig) This is the format of your plot grid: [ (1,1) x1,y1 ] [ (1,2) x2,y2 ] Inset Plots To display a subplot as inset, we need to configure its trace object. First the xaxis and yaxis properties of inset trace to ‘x2’ and ‘y2’ respectively. Following statement puts ‘log’ trace in inset. trace2 = go.Scatter( x = x, y = y2, xaxis = ”x2”, yaxis = ”y2”, name = ”log” ) Secondly, configure Layout object where the location of x and y axes of inset is defined by domain property that specifies is position with respective to major axis. xaxis2=dict( domain = [0.1, 0.5], anchor = ”y2” ), yaxis2 = dict( domain = [0.5, 0.9], anchor = ”x2” ) Complete script to display log trace in inset and exp trace on main axis is given below − trace1 = go.Scatter( x = x, y = y1, name = ”exp” ) trace2 = go.Scatter( x = x, y = y2, xaxis = ”x2”, yaxis = ”y2”, name = ”log” ) data = [trace1, trace2] layout = go.Layout( yaxis = dict(showline = True), xaxis2 = dict( domain = [0.1, 0.5], anchor = ”y2” ), yaxis2 = dict( showline = True, domain = [0.5, 0.9], anchor = ”x2” ) ) fig = go.Figure(data=data, layout=layout) iplot(fig) The output is mentioned below − Print Page Previous Next Advertisements ”;