Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
suyashi29
GitHub Repository: suyashi29/python-su
Path: blob/master/Data Visualization using Python/3.Data Visualization using Plotty.ipynb
3074 views
Kernel: Python 3 (ipykernel)

Plotly

  • is an open-source module of Python which is used for data visualization

  • supports various graphs like line charts, scatter plots, bar charts, histograms, area plot, etc

image.png

  • Plotly uses javascript behind the scenes and is used to make interactive plots where we can zoom in on the graph or add additional information like data on hover

  • Plotly does not come built-in with Python. To install it type the below command in the terminal.

pip install plotly pip install wordcloud --trusted-host pypi.org --trusted-host files.pythonhosted.org plotly
import plotly.express as px # Creating the Figure instance fig = px.line(x=[1, 2], y=[3, 4]) # printing the figure instance print(fig)
Figure({ 'data': [{'hovertemplate': 'x=%{x}<br>y=%{y}<extra></extra>', 'legendgroup': '', 'line': {'color': '#636efa', 'dash': 'solid'}, 'marker': {'symbol': 'circle'}, 'mode': 'lines', 'name': '', 'orientation': 'v', 'showlegend': False, 'type': 'scatter', 'x': array([1, 2], dtype=int64), 'xaxis': 'x', 'y': array([3, 4], dtype=int64), 'yaxis': 'y'}], 'layout': {'legend': {'tracegroupgap': 0}, 'margin': {'t': 60}, 'template': '...', 'xaxis': {'anchor': 'y', 'domain': [0.0, 1.0], 'title': {'text': 'x'}}, 'yaxis': {'anchor': 'x', 'domain': [0.0, 1.0], 'title': {'text': 'y'}}} })

Creating Line Chart

# using the iris dataset iris_data = px.data.iris() iris_data
iris_data.describe()
import plotly.express as px # using the iris dataset iris_data = px.data.iris() # plotting the line chart fig = px.line(iris_data, y="sepal_width",) # showing the plot fig.show()

line dash parameter which is used to group the lines according to the dataframe column passed.

import plotly.express as px # using the iris dataset iris_data = px.data.iris() # plotting the line chart fig = px.line(iris_data, y="sepal_width", line_group='species') # showing the plot fig.show()

group and color the data according to the species.

import plotly.express as px # using the iris dataset iris_data = px.data.iris() # plotting the line chart fig = px.line(iris_data, y="sepal_width", line_dash='species', color='species') # showing the plot fig.show()

Bar Chart

d
import plotly.express as px # Loading the data d = px.data.tips() # Creating the bar chart fig = px.bar(d, x='day', y="total_bill") fig.show()

Customize Bars

  • color: Used to color the bars.

  • facet_row: Divides the graph into rows according to the data passed

  • facet_col: Divides the graph into columns according to the data passed

import plotly.express as px # Loading the data d = px.data.tips() # Creating the bar chart fig = px.bar(d, x='day', y="total_bill", color='sex', facet_row='time', facet_col='sex') fig.show()

Scatter Plot

import plotly.express as px # using the dataset d = px.data.tips() # plotting the scatter chart fig = px.scatter(d, x='total_bill', y="tip") # showing the plot fig.show()

customizations for Scatter Chart

color: Color the points. symbol: Gives a symbol to each point according to the data passed. size: The size for each point.

import plotly.express as px # using the dataset d = px.data.tips() # plotting the scatter chart fig = px.scatter(d, x='total_bill', y="tip", color='time', symbol='sex', size='size', facet_row='day', facet_col='time') # showing the plot fig.show()

Histogram

import plotly.express as px # using the dataset df = px.data.tips() # plotting the histogram fig = px.histogram(df, x="total_bill") # showing the plot fig.show()

Customizations with Histogram

  • color: To color the bars

  • nbins: To set the number of bins

  • histnorm: Mode through which the bins are represented. Different values that can be passed using this argument are-

  • percent or probability: The output of histfunc for a given bin is divided by the sum of the output of histfunc for all bins.

  • density: The output of histfunc for a given bin is divided by the size of the bin.

  • probability density: The output of histfunc for a given bin is normalized such that it corresponds to the probability that a random

  • barmode: Can be either ‘group’, ‘overlay’ or ‘relative’.

  • group: Bars are stacked above zero for positive values and below zero for negative values

  • overlay: Bars are drawn on the top of each other

  • group: Bars are placed beside each other.

import plotly.express as px # using the dataset df = px.data.tips() # plotting the histogram fig = px.histogram(df, x="total_bill", color='sex', nbins=50, histnorm='percent', barmode='overlay') # showing the plot fig.show()

Pie Chart

import plotly.express as px # Loading the iris dataset df = px.data.tips() fig = px.pie(df, values="total_bill", names="day") fig.show()

Customizations to Donut Chart–

  • color_discrete_sequence: Strings defining valid CSS colors

  • opacity: Opacity for markers. The value should be between 0 and 1

  • hole: Creates a hole in between to make it a donut chart. The value should be between 0 and 1

import plotly.express as px # Loading the iris dataset df = px.data.tips() fig = px.pie(df, values="total_bill", names="day", color_discrete_sequence=px.colors.sequential.RdBu, opacity=0.7, hole=0.5) fig.show()

BoxPlot

import plotly.express as px # using the dataset df = px.data.tips() # plotting the boxplot fig = px.box(df, x="day", y="tip") # showing the plot fig.show()

Adding interaction to the plot

A drop-down menu is a part of the menu button which is displayed on a screen all the time. Every menu button is associated with a Menu widget that can display the choices for that menu button when clicked on it. In plotly, there are 4 possible methods to modify the charts by using update menu method.

  • restyle: modify data or data attributes

  • relayout: modify layout attributes

  • update: modify data and layout attributes

  • animate: start or pause an animation

d
import plotly.graph_objects as px import numpy as np import pandas as pd plot = px.Figure(data=[px.Scatter( x=d['day'], y=d['tip'], mode='markers',) ]) # Add dropdown plot.update_layout( updatemenus=[ dict(buttons=list([ dict( args=["type", "scatter"], label="Scatter Plot", method="restyle" ), dict( args=["type", "bar"], label="Bar Chart", method="restyle" ) ]), direction="down", ), ] ) plot.show()
import plotly.graph_objects as px plot = px.Figure(data=[px.Scatter( x=d['day'], y=d['tip'], mode='markers',) ]) # Add dropdown plot.update_layout( updatemenus=[ dict( type="buttons", direction="left", buttons=list([ dict( args=["type", "scatter"], label="Scatter Plot", method="restyle" ), dict( args=["type", "bar"], label="Bar Chart", method="restyle" ) ]), ), ] ) plot.show()
import plotly.graph_objects as px import plotly.express as go import numpy as np df = go.data.tips() x = df['total_bill'] y = df['tip'] plot = px.Figure(data=[px.Scatter( x=x, y=y, mode='markers',) ]) plot.update_layout( xaxis=dict( rangeselector=dict( buttons=list([ dict(count=1, step="day", stepmode="backward"), ]) ), rangeslider=dict( visible=True ), ) ) plot.show()