Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Plotly Cheatsheet



The Plotly Cheatsheet provides the fundamental guide to learn Plotly for data visualization. This library helps users to create interactive charts such as line graphs, bar charts, scatter plots, and 3D visuals. Thus, this makes data easy to understand by writing a few lines of code. Go through this cheat sheet and learn the Plotly library of Python.

1. Basic Overview of Plotly

In the introduction, the Python library Plotly is used to create interactive, high-quality visualizations, containing line charts, bar charts, scatter plots, 3D plots, maps, and dashboards.

2. Installation

To install the plotly library in python, use the following command −

pip install plotly

3. Import Plotly

To import the plotly library, write the following lines of code −

i. For Plotly Express

import plotly.express as px

ii. For Plotly Graph Object

import plotly.graph_objects as go

4. Legends

In Plotly, a legend is a component that displays the color, shape, and size of each trace in a graph.

import plotly.express as px

# given data
data = {
    "Category": ["A", "B", "C", "A", "B", "C"],
    "X": [1, 2, 3, 4, 5, 6],
    "Y": [10, 15, 7, 20, 25, 13]
} 

import pandas as pd
df = pd.DataFrame(data)

# Create Scatter Plot
fig = px.scatter(df, x="X", y="Y", color="Category", title="Plotly Legend Example")

# Customize Legend
fig.update_layout(
    legend_title="Legend",
    showlegend=True  
)

# Show Plot
fig.show()

The above code produces the following result −

legend_in_plotly.jpg

5. Format Axis and Ticks

In Plotly, a formatted axis is a way to customize the appearance of a specific axis in a graph.

import plotly.express as px

# iris dataset(sample)
df = px.data.iris()

# Create Scatter Plot
fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", title="Axis Formatting")
# Customize Axis
fig.update_layout(

    # set the label for x and y axis
    xaxis_title="Sepal Width (cm)",  
    yaxis_title="Sepal Length (cm)", 
	
	# set the range for x and y axis
    xaxis_range=[2, 5], 
    yaxis_range=[4, 8]  
)
fig.show()

The above code produces the following result −

axis_formatting_in_plotly.jpg

In Plotly, ticks are defined using small lines that mark the specific points on the x and y axes of the graph.

fig.update_layout(xaxis=dict(tickmode='linear', tick0=1, dtick=1, ticks='outside', ticklen=8, tickwidth=2, tickcolor='blue', tickangle=45, showticklabels=True, tickprefix='Day ', ticksuffix='th'))

6. Subplots and Inset Plots

Subplots allow multiple plots in a single figure, while inset plots are smaller plots inside a main plot.

import plotly.subplots as sp
import plotly.graph_objects as go

fig = sp.make_subplots(rows=1, cols=2)
fig.add_trace(go.Scatter(y=[1, 3, 2], mode='lines', name='Line'), row=1, col=1)
fig.add_trace(go.Bar(y=[3, 1, 2], name='Bar'), row=1, col=2)
fig.show()

The above code produces the following result −

subplot_and_inset_plots_in_plotly.jpg

7. Line Plots

Line plots are used to visualize data trends over time.

import plotly.express as px
df = px.data.gapminder()
fig = px.line(df[df['country'] == 'India'], x='year', y='gdpPercap', title='GDP Over Time')
fig.show()

The above code produces the following result −

line_plots_in_plotly.jpg

8. Bar Plots

Bar plots display categorical data with rectangular bars representing values.

df = px.data.tips()
fig = px.bar(df, x='day', y='total_bill', color='sex', title='Bar Plot of Total Bill by Day')
fig.show()

The above code produces the following result −

bar_plots_in_plotly.jpg

9. Pie Chart

Pie charts show proportions of a whole as slices.

fig = px.pie(df, names='day', values='total_bill', title='Total Bill Distribution by Day')
fig.show()

The above code produces the following result −

pie_charts_in_plotly.jpg

10. Scatter Plots

Scatter plots show relationships between two numerical variables.

fig = px.scatter(df, x='total_bill', y='tip', color='sex', title='Tip vs Total Bill')
fig.show()

The above code produces the following result −

scatter_plots_in_plotly.jpg

11. Scattergl Plots

Scattergl plots are optimized for large datasets.

fig = go.Figure(data=go.Scattergl(x=df['total_bill'], y=df['tip'], mode='markers'))
fig.show()

The above code produces the following result −

scattergl_plots_in_plotly.jpg

12. Box Plot

Box plots summarize data distribution using quartiles.

fig = px.box(df, x='day', y='total_bill', color='sex', title='Box Plot of Total Bill by Day')
fig.show()

The above code produces the following result −

box_plots_in_plotly.jpg

13. Violin Plot

Violin plots show data distribution density and quartiles.

fig = px.violin(df, x='day', y='total_bill', color='sex', box=True, title='Violin Plot of Total Bill by Day')
fig.show()

The above code produces the following result −

violin_plots_in_plotly.jpg

14. Contour Plot

Contour plots represent 3D data in 2D using contour lines.

import numpy as np
x = np.linspace(-2, 2, 100)
y = np.linspace(-2, 2, 100)
X, Y = np.meshgrid(x, y)
Z = np.sin(X**2 + Y**2)
fig = go.Figure(data=go.Contour(z=Z, x=x, y=y))
fig.show()

The above code produces the following result −

contour_plots_in_plotly.jpg

15. 3D Scatter and Surface Plot

3D scatter and surface plots visualize 3D data.

fig = go.Figure(data=[go.Surface(z=Z)])
fig.show()

The above code produces the following result −

3d_scatter_and_surface_plots.jpg

16. Histograms

Histograms represent frequency distribution of numerical data.

fig = px.histogram(df, x='total_bill', nbins=20, title='Histogram of Total Bill')
fig.show()

The above code produces the following result −

histogram_in_plotly.jpg

17. Heatmaps

Heatmaps use colors to represent matrix values.

fig = go.Figure(data=go.Heatmap(z=Z, x=x, y=y))
fig.show()

The above code produces the following result −

heatmap_in_plotly.jpg

18. Polar Chart

Polar charts display data in a circular coordinate system.

fig = px.line_polar(r=[1, 2, 3, 4], theta=[0, 45, 90, 135], title='Polar Chart')
fig.show()

The above code produces the following result −

polar_charts_in_plotly.jpg

19. Radar Chart

Radar charts show multi-variable data as a polygon.

fig = go.Figure()
fig.add_trace(go.Scatterpolar(r=[1, 2, 3], theta=['A', 'B', 'C'], fill='toself'))
fig.show()

The above code produces the following result −

radar_charts_in_plotly.jpg

20. OHLC Chart

OHLC (Open-High-Low-Close) charts are used to visualize stock price movements.

data = go.Ohlc(x=['2024-02-01', '2024-02-02', '2024-02-03'], open=[100, 110, 105], high=[115, 120, 110], low=[95, 100, 102], close=[110, 108, 107])
fig = go.Figure(data=[data])
fig.show()

The above code produces the following result −

ohlc_charts_in_plotly.jpg

21. Waterfall Chart

Waterfall charts are used to show cumulative changes in values.

fig = go.Figure(go.Waterfall(name='Profit', orientation='v', measure=['relative', 'relative', 'total'], x=['Revenue', 'Expenses', 'Net Profit'], y=[2000, -500, 1500]))
fig.show()

The above code produces the following result −

waterfall_charts_in_plotly.jpg

22. Customizing Plots in Plotly

User can customize Plotly plots with titles, labels, and colors.

fig.update_layout(title='Customized Plot', xaxis_title='X Label', yaxis_title='Y Label', template='plotly_dark')
fig.show()

The above code produces the following result −

customize_plot_in_plotly.jpg

23. Customizing Markers in Plotly

Customize marker size, shape, and color in scatter plots.

import plotly.graph_objects as go
x = [1, 2, 3, 4, 5]
y = [10, 15, 7, 12, 9]

# Create scatter plot with customized markers
fig = go.Figure()

fig.add_trace(go.Scatter(
    x=x, 
    y=y, 
    mode='markers',
    marker=dict(
        size=15,           
        color='green',       
        symbol='star',    
        opacity=0.7,       
        line=dict(
            color='black', 
            width=2        
        )
    )
))

# Show plot
fig.show()

The above code produces the following result −

customize_markers_in_plotly.jpg

24. Customizing Lines in Plotly

To customize the lines in Plotly change line styles such as width, color, and dash patterns.

import plotly.graph_objects as go

# given data
x = [1, 2, 3, 4, 5]
y = [10, 15, 7, 12, 9]

# Create a line plot with custom styling
fig = go.Figure()

fig.add_trace(go.Scatter(
    x=x, 
    y=y, 
    mode='lines',  # Only line, no markers
    line=dict(
        color='blue',   
        width=3,        
        dash='dashdot'   
    )
))
# Show the plot
fig.show()

The above code produces the following result −

customize_lines_in_plotly.jpg
Advertisements