Plotly
Plotly
1. Installing Plotly
First, you need to install Plotly. You can do this by running:
bash
Copy code
!pip install plotly
python
Copy code
import plotly.graph_objects as go
# Sample data
x = [1, 2, 3, 4, 5]
y = [10, 15, 13, 17, 10]
Ploty 1
go.Figure() : This creates a figure where you can add multiple traces (lines,
bars, etc.).
go.Scatter() : This adds a trace (here, a line plot). You can change the mode to
'markers' , 'lines' , or 'lines+markers' for different types of plots.
3. Scatter Plot
python
Copy code
# Add a scatter plot with markers
fig = go.Figure()
fig.show()
You can customize the marker shape, size, and color like this:
python
Copy code
fig.add_trace(go.Scatter(
x=x,
y=y,
mode='markers',
marker=dict(size=12, color='red', symbol='circle'),
name='Custom Scatter'
))
4. Bar Chart
Ploty 2
python
Copy code
# Bar chart
fig = go.Figure()
fig.show()
5. Histogram
python
Copy code
# Histogram
import numpy as np
# Plot histogram
fig = go.Figure(data=[go.Histogram(x=random_data)])
fig.show()
6. Pie Chart
python
Copy code
# Pie chart
labels = ['A', 'B', 'C', 'D']
values = [10, 20, 30, 40]
Ploty 3
# Create the pie chart
fig = go.Figure(data=[go.Pie(labels=labels, values=values)])
fig.show()
python
Copy code
# Multiple line plot
fig = go.Figure()
fig.show()
8. Customizing Layout
You can customize the layout of the plot (titles, axis labels, background colors,
etc.):
python
Copy code
# Customize layout
fig.update_layout(
title='My Custom Plot',
Ploty 4
xaxis_title='X Axis',
yaxis_title='Y Axis',
plot_bgcolor='rgba(0, 0, 0, 0)', # Transparent backgroun
d
paper_bgcolor='rgba(0, 0, 0, 0)' # Transparent figure ba
ckground
)
fig.show()
9. Interactive Features
Plotly provides built-in interactivity such as hover, zoom, and pan. However, you
can control how hover information is displayed:
python
Copy code
# Customize hover
fig.update_traces(
hoverinfo='x+y', # Show both x and y coordinates on hove
r
hoverlabel=dict(
bgcolor="white",
font_size=16,
font_family="Rockwell"
)
)
10. Subplots
You can create subplots using make_subplots to display multiple charts in one
figure:
Ploty 5
python
Copy code
from plotly.subplots import make_subplots
fig.show()
11. 3D Plots
Plotly also supports 3D plotting:
python
Copy code
# 3D plot
x = [1, 2, 3, 4, 5]
y = [10, 20, 30, 40, 50]
z = [5, 10, 15, 20, 25]
fig.update_layout(
title='3D Scatter Plot',
scene=dict(xaxis_title='X', yaxis_title='Y', zaxis_title
='Z')
)
Ploty 6
fig.show()
python
Copy code
# Save as an HTML file
fig.write_html('my_plot.html')
bash
Copy code
!pip install -U kaleido
13. Animation
You can create animated charts in Plotly by changing data over time:
python
Copy code
# Animation example
import plotly.express as px
df = px.data.gapminder()
Ploty 7
# Create animated scatter plot
fig = px.scatter(df, x="gdpPercap", y="lifeExp", animation_fr
ame="year", animation_group="country",
size="pop", color="continent", hover_name="c
ountry", log_x=True, size_max=60)
fig.show()
Ploty 8