Plotly - Tutorialspoint

Transcription

Plotlyi

PlotlyAbout the TutorialThis tutorial is about Canada based technical computing company Plotly which is alsoknown for its URL. Here, you will learn about how to develop data analytics andvisualization tools. Moreover, this tutorial describes the features of Plotly’s Pythongraphing library to make interactive and publication-ready graphs for both online andoffline viewing.AudienceThe tutorial is aptly designed for all those who are passionate about learning onlinegraphing, analytics, and statistics tools. Furthermore, it is for those individuals who havekeen interest in understanding how Plotly helps in providing tools for scientific graphinglibraries of the computer programming languages such as Python, R, MATLAB, Perl, Julia,Arduino, and REST.PrerequisitesTo work with Plotly, you need to create an account on the official website. The detailsabout how to create an account and get login is discussed in the tutorial. If you are noviceto knowledge about data analytics, visualization tools or any of the programminglanguages like Python, R, MATLAB, Arduino, REST, Julia and Perl, we suggest you to gothrough tutorials related to these before proceeding with this tutorial.Copyright & Disclaimer Copyright 2019 by Tutorials Point (I) Pvt. Ltd.All the content and graphics published in this e-book are the property of Tutorials Point (I)Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy, distribute or republishany contents or a part of contents of this e-book in any manner without written consentof the publisher.We strive to update the contents of our website and tutorials as timely and as precisely aspossible, however, the contents may contain inaccuracies or errors. Tutorials Point (I) Pvt.Ltd. provides no guarantee regarding the accuracy, timeliness or completeness of ourwebsite or its contents including this tutorial. If you discover any errors on our website orin this tutorial, please notify us at contact@tutorialspoint.comii

PlotlyTable of ContentsAbout the Tutorial . iiAudience . iiPrerequisites . iiCopyright & Disclaimer . iiTable of Contents . iii1.Plotly — Introduction. 12.Plotly — Environment Setup . 2Installation of Python package . 23.Plotly — Online and Offline Plotting . 6Settings for online plotting . 6Setting for Offline Plotting . 84.Plotly — Plotting Inline with Jupyter Notebook . 105.Plotly — Package Structure . 126.Plotly — Exporting to Static Images . 147.Plotly — Legends . 168.Plotly — Format Axis and Ticks . 18Plot with Axis and Tick . 18Plot with Multiple Axes . 209.Plotly — Subplots and Inset Plots. 22Making Subplots . 22Inset Plots . 2410. Plotly — Bar Chart and Pie Chart . 26Bar Chart . 26Pie chart. 2911. Plotly — Scatter Plot, Scattergl Plot and Bubble Charts. 33Scatter Plot . 33iii

PlotlyScattergl Plot . 34Bubble charts . 3512. Plotly — Dot Plots and Table . 38Dot Plots . 38Table in Plotly . 3913. Plotly — Histogram . 4214. Plotly — Box Plot, Violin Plot and Contour Plot. 45Box Plot. 45Violin Plot . 47Contour plot . 48Quiver plot . 5015. Plotly — Distplots, Density Plot and Error Bar Plot. 52Distplots . 52Density Plot . 53Error Bar Plot . 5416. Plotly — Heatmap . 5817. Plotly — Polar Chart and Radar Chart . 60Polar Chart . 60Radar chart . 6218. Plotly — OHLC Chart, Waterfall Chart and Funnel Chart . 64OHLC Chart . 64Waterfall chart . 66Funnel Chart . 6719. Plotly — 3D Scatter and Surface Plot . 683D Scatter Plot . 683D Surface Plot . 6920. Plotly — Adding Buttons/Dropdown. 7121. Plotly — Slider Control . 78iv

Plotly22. Plotly — FigureWidget Class . 8023. Plotly with Pandas and Cufflinks . 84Pandas dataframes from databases . 8624. Plotly with Matplotlib and Chart Studio . 87Matplotlib . 87Chart Studio . 88v

1. Plotly — IntroductionPlotlyPlotly is a Montreal based technical computing company involved in development of dataanalytics and visualisation tools such as Dash and Chart Studio. It has also developedopen source graphing Application Programming Interface (API) libraries for Python, R,MATLAB, Javascript and other computer programming languages.Some of the important features of Plotly are as follows: It produces interactive graphs. The graphs are stored in JavaScript Object Notation (JSON) data format so thatthey can be read using scripts of other programming languages such as R, Julia,MATLAB etc. Graphs can be exported in various raster as well as vector image formats1

2. Plotly — Environment SetupPlotlyThis chapter focusses on how to do the environmental set up in Python with the help ofPlotly.Installation of Python packageIt is always recommended to use Python’s virtual environment feature for installation of anew package. Following command creates a virtual environment in the specified folder.python -m myenvTo activate the so created virtual environment run activate script in bin sub folder asshown below.source bin/activateNow we can install plotly’s Python package as given below using pip utility.pip install plotlyYou may also want to install Jupyter notebook app which is a web based interface toIpython interpreter.pip install jupyter notebookFirstly, you need to create an account on website which is available at https://plot.ly. Youcan sign up by using the link mentioned herewith https://plot.ly/api signup and then login successfully.2

PlotlyNext, obtain the API key from settings page of your dashboard.3

PlotlyUse your username and API key to set up credentials on Python interpreter session.import plotlyplotly.tools.set credentials file(username 'test',api key '********************')A special file named credentials is created in .plotly subfolder under your homedirectory. It looks similar to the following:{"username": "test","api key": "********************","proxy username": "",4

Plotly"proxy password": "","stream ids": []}In order to generate plots, we need to import the following module from plotly package:import plotly.plotly as pyimport plotly.graph objs as goplotly.plotly module contains the functions that will help us communicate with the Plotlyservers. Functions in plotly.graph objs module generates graph objects.5

3. Plotly — Online and Offline PlottingPlotlyThe following chapter deals with the settings for the online and offline plotting. Let us firststudy the settings for online plotting.Settings for online plottingData and graph of online plot are save in your plot.ly account. Online plots aregenerated by two methods both of which create a unique url for the plot and save it inyour 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 thenotebook.We shall now display simple plot of angle in radians vs. its sine value. First, obtainndarray 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 ofangles in x which has to be displayed on y axis are obtained by following statements:import numpy as npimport math #needed for definition of pixpoints 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.pyimport plotlyplotly.tools.set credentials file(username 'lathkar',api key '********************')import plotly.plotly as pyimport plotly.graph objs as go6

Plotlyimport numpy as npimport math #needed for definition of pixpoints 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 displayedin the browser at specified URL as stated below. python plotly1.pyHigh five! You successfully sent some data to your account on plotly. View yourplot in your browser at https://plot.ly/ lathkar/0Just above the displayed graph, you will find tabs Plot, Data, Python &Rand Forking history.7

PlotlyCurrently, 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 PlottingPlotly allows you to generate graphs offline and save them in local machine. Theplotly.offline.plot() function creates a standalone HTML that is saved locally and openedinside your web browser.Use plotly.offline.iplot() when working offline in a Jupyter Notebook to display theplot 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 tempplot.html will be created locally and opened in web browser.plotly.offline.plot({ "data": data,"layout": go.Layout(title "hello world")},auto open True)8

Plotly9

4. Plotly — Plotting Inline with JupyterNotebookPlotlyIn 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 notebookmode as follows:from plotly.offline import init notebook modeinit notebook mode(connected True)Keep rest of the script as it is and run the notebook cell by pressing Shift Enter. Graphwill be displayed offline inside the notebook itself.import plotlyplotly.tools.set credentials file(username 'lathkar', api key '************')from plotly.offline import iplot, init notebook modeinit notebook mode(connected True)import plotlyimport plotly.graph objs as goimport numpy as npimport math #needed for definition of pixpoints 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:10

PlotlyThe 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.11

5. Plotly — Package StructurePlotlyPlotly Python package has three main modules which are given below: plotly.plotly plotly.graph objs plotly.toolsThe 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 theclass definitions for the objects that make up the plots you see. Following graph objectsare defined: Figure, Data, Layout, Different graph traces like Scatter, Box, Histogram etc.All graph objects are dictionary- and list-like objects used to generate and/or modify everyfeature of a Plotly plot.The plotly.tools module contains many helpful functions facilitating and enhancing thePlotly experience. Functions for subplot generation, embedding Plotly plots in IPythonnotebooks, saving and retrieving your credentials are defined in this module.A plot is represented by Figure object which represents Figure class defined inplotly.graph objs module. It’s constructor needs following parameters:import plotly.graph objs as gofig go.Figure(data, layout, frames)12

PlotlyThe data parameter is a list object in Python. It is a list of all the traces that you wish toplot. A trace is just the name we give to a collection of data which is to be plotted. A traceobject 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 eachis returned by respective functions in graph objs functions. For example: go.scatter()returns a scatter trace.import numpy as npimport math #needed for definition of pixpoints 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 areunrelated 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 indicateother descriptions.Finally, there is a Figure object created by go.Figure() function. It is a dictionary-likeobject that contains both the data object and the layout object. The figure object iseventually plotted.py.iplot(fig)13

6. Plotly — Exporting to Static ImagesPlotlyOutputs of offline graphs can be exported to various raster and vector image formats. Forthat purpose, we need to install two dependencies – orca and psutil.OrcaOrca stands for Open-source Report Creator App. It is an Electron app that generatesimages and reports of plotly graphs, dash apps, dashboards from the command line. Orcais the backbone of Plotly's Image Server.psutilpsutil (python system and process utilities) is a cross-platform library for retrievinginformation on running processes and system utilization in Python. It implements manyfunctionalities 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 psutilIf you are using Anaconda distribution of Python, installation of orca and psutil is veryeasily done by conda package manager as follows:conda install -c plotly plotly-orca psutilSince, orca is not available in PyPi repository. You can instead use npm utility to installit.npm install -g electron@1.8.4 orcaUse pip to install psutilpip install psutilIf you are not able to use npm or conda, prebuilt binaries of orca can also be downloadedfrom 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 moduleimport plotly.io as pioNow, 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.14

PlotlyPio.write image(fig, ‘sinewave.svg’)pio.write image(fig, ‘sinewave.pdf’)In Jupyter notebook, the image object obtained by pio.to image() function can bedisplayed inline as follows:15

7. Plotly — LegendsPlotlyBy default, Plotly chart with multiple traces shows legends automatically. If it has only onetrace, it is not displayed automatically. To display, set showlegend parameter of Layoutobject to True.layout go.Layoyt(showlegend True)Default labels of legends are trace object names. To set legend label explicitly set nameproperty of trace.In following example, two scatter traces with name property are plotted.import numpy as npimport math #needed for definition of pixpoints np.arange(0, math.pi*2, 0.05)y1 np.sin(xpoints)y2 np.cos(xpoints)trace0 go.Scatter(x xpoints,y y1,name 'Sine')trace1 go.Scatter(x xpoints,y y2,name 'cos')data [trace0, trace1]layout go.Layout(title "Sine and cos", xaxis {'title':'angle'},yaxis {'title':'value'})fig go.Figure(data data, layout layout)iplot(fig)The plot appears as below:16

Plotly17

8. Plotly — Format Axis and TicksPlotlyYou can configure appearance of each axis by specifying the line width and color. It is alsopossible to define grid width and grid color. Let us learn about the same in detail in thischapter.Plot with Axis and TickIn the Layout object’s properties, setting showticklabels to true will enable ticks. Thetickfont property is a dict object specifying font name, size, color, etc. The tickmodeproperty can have two possible values — linear and array. If it is linear, the position ofstarting 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 andticktext properties.The Layout object also has Exponentformat attribute set to ‘e’ will cause tick values tobe 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 specifyingline, 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',18

Plotlylinewidth 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))19

PlotlyPlot with Multiple AxesSometimes it is useful to have dual x or y axes in a figure; for example, when plottingcurves with different units together. Matplotlib supports this with the twinxand twiny functions. In the following example, the plot has dual y axes, one showingexp(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'))20

Plotlyfig go.Figure(data data, layout layout)iplot(fig)Here, additional y axis is configured as yaxis2 and appears on right side, having ‘log’ astitle. Resultant plot is as follows:21

9. Plotly — Subplots and Inset PlotsPlotlyHere, we will understand the concept of subplots and inset plots in Plotly.Making SubplotsSometimes it is helpful to compare different views of data side by side. This supports theconcept of subplots. It offers make subplots() function in plotly.tools module. Thefunction 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 thefigure.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. usingupdate() method.fig['layout'].update(height 600, width 800, title 'subplots')Here's the complete script:from plotly import toolsimport plotly.plotly as pyimport plotly.graph objs as gofrom plotly.offline import iplot, init notebook modeinit notebook mode(connected True)import numpy as npx np.arange(1,11)y1 np.exp(x)y2 np.log(x)trace1 go.Scatter(x x,y y1,name 'exp')trace2 go.Scatter(22

Plotlyx 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 ]23

PlotlyInset PlotsTo display a subplot as inset, we need to configure its trace object. First the xaxis andyaxis 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 bydomain 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]24

Plotlylayout 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:25

10. Plotly — Bar Chart and Pie ChartPlotlyIn this chapter, we will learn how to make bar and pie charts with the help of Plotly. Letus begin by understanding about bar chart.Bar ChartA bar chart presents categorical data with rectangular bars with heights or lengthsproportional to the values that they represent. Bars can be displayed vertically orhorizontally. It helps to show comparisons among discrete categories. One axis of thechart shows the specific categories being compared, and the other axis represents ameasured value.Following example plots a simple bar chart about number of students enrolled for differentcourses. The go.Bar() function returns a bar trace with x coordinate set as list of subjectsand y coordinate as number of students.import plotly.graph objs as golangs ['C', 'C ', 'Java', 'Python', 'PHP']students [23,17,35,29,12]data [go.Bar(x langs,y students)]fig go.Figure(data data)iplot(fig)The output will be as shown below:26

PlotlyTo display a grouped bar chart, the barmode property of Layout object must be set togroup. In the following code, multiple traces representing students in each year areplotted against subjects and shown as grouped bar chart.branches ['CSE', 'Mech', 'Electronics']fy [23,17,35]sy [20, 23, 30]ty [30,20,15]trace1 go.Bar(x branches,y fy,name 'FY')trace2 go.Bar(x branches,y sy,name 'SY')trace3 go.Bar(27

Plotlyx branches,y ty,name 'TY')data [trace1, trace2, trace3]layout go.Layout(barmode 'group')fig go.Figure(data data, layout layout)iplot(fig)The output of the same is as follows:The barmode property determines how bars at the same location coordinate are displayedon the graph. Defined values are "stack" (bars stacked on top of one another), "relative",(bars are stacked on top of one another, with negative values below the axis, positivevalues above), "group" (bars plotted next to one another).By changing barmode property to ‘stack’ the plotted graph appears as below:28

PlotlyPie chartA Pie Chart displays only one series of data. Pie charts show the size of items (calledwedge) in one data series, proportional to the sum of the items. Data points are shownas a perc

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