Matplotlib vs Plotly

Plotly and Matplotlib are two of the most widely used libraries for data visualization in Python. Both are powerful tools, but they have different strengths and weaknesses that make them suited to different types of projects. This tutorial will compare Plotly and Matplotlib to help you decide which library to use for your specific needs.

### Overview

#### Matplotlib
Matplotlib is a versatile and widely-used plotting library that offers extensive customization options. It is well-suited for creating static, high-quality visualizations and is the foundation for many other plotting libraries, such as Seaborn and Pandas plotting.

#### Plotly
Plotly is an interactive graphing library that allows for the creation of dynamic and visually appealing plots. It offers built-in interactivity, which can be integrated easily into web applications. Plotly is great for dashboards and presentations where user interaction is key.

### Line Plot

Let's start with creating a basic line plot in both Plotly and Matplotlib.

#### Matplotlib

import matplotlib.pyplot as plt

x = [0, 1, 2, 3, 4, 5]
y = [0, 1, 4, 9, 16, 25]

plt.plot(x, y, marker='o')
plt.title('Matplotlib Line Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.grid(True)
plt.show()
#### Plotly

import plotly.graph_objects as go

x = [0, 1, 2, 3, 4, 5]
y = [0, 1, 4, 9, 16, 25]

fig = go.Figure(data=go.Scatter(x=x, y=y, mode='lines+markers'))
fig.update_layout(title='Plotly Line Plot', xaxis_title='X-axis', yaxis_title='Y-axis')
fig.show()
### Bar Plots

#### Matplotlib

import matplotlib.pyplot as plt

# Sample data
categories = ['A', 'B', 'C', 'D']
values = [10, 24, 36, 15]

plt.bar(categories, values, color='skyblue')
plt.title('Matplotlib Bar Plot')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.show()
#### Plotly

import plotly.graph_objects as go

# Sample data
categories = ['A', 'B', 'C', 'D']
values = [10, 24, 36, 15]

fig = go.Figure(data=[go.Bar(x=categories, y=values, marker_color='skyblue')])
fig.update_layout(title='Plotly Bar Plot', xaxis_title='Categories', yaxis_title='Values')
fig.show()
### Scatter Plots

#### Matplotlib

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [10, 27, 35, 40, 45]
sizes = [20, 50, 100, 150, 200]

plt.scatter(x, y, s=sizes, color='red', alpha=0.5)
plt.title('Matplotlib Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.show()
#### Plotly

import plotly.express as px

# Sample data
data = {'x': [1, 2, 3, 4, 5], 'y': [10, 27, 35, 40, 45], 'sizes': [20, 50, 100, 150, 200]}

fig = px.scatter(data, x='x', y='y', size='sizes', color_discrete_sequence=['red'])
fig.update_layout(title='Plotly Scatter Plot', xaxis_title='X-axis', yaxis_title='Y-axis')
fig.show()
### Histograms

#### Matplotlib

import matplotlib.pyplot as plt
import numpy as np

# Sample data
data = np.random.randn(1000)

plt.hist(data, bins=30, color='green', edgecolor='black', alpha=0.7)
plt.title('Matplotlib Histogram')
plt.xlabel('Data Value')
plt.ylabel('Frequency')
plt.show()
#### Plotly

import plotly.express as px
import numpy as np

# Sample data
data = np.random.randn(1000)

fig = px.histogram(data, nbins=30, color_discrete_sequence=['green'], opacity=0.7)
fig.update_layout(title='Plotly Histogram', xaxis_title='Data Value', yaxis_title='Frequency')
fig.show()
### Customization and Styling

Both **Matplotlib** and **Plotly** offer extensive customization options to tailor your plots for different aesthetics and functional requirements.

#### **Matplotlib**

Matplotlib allows for a high degree of customization, making it easy to fine-tune the appearance of plots.

import matplotlib.pyplot as plt
import numpy as np

# Generate some data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create a basic plot
plt.figure(figsize=(10, 6))
plt.plot(x, y, label='Sine Wave', color='blue', linewidth=2)

# Adding title and labels
plt.title('Sine Wave Example', fontsize=16)
plt.xlabel('X Axis', fontsize=14)
plt.ylabel('Y Axis', fontsize=14)

# Customizing tick parameters
plt.xticks(fontsize=12, rotation=45)
plt.yticks(fontsize=12)

# Adding grid
plt.grid(True, which='both', linestyle='--', linewidth=0.5)

# Adding legend
plt.legend()

# Annotating a point
plt.annotate('Peak', xy=(1.57, 1), xytext=(3, 1.5),
             arrowprops=dict(facecolor='black', shrink=0.05))

# Customize the spines
for spine in plt.gca().spines.values():
    spine.set_visible(False)

# Show the plot
plt.show()
This code generates a sine wave plot and applies various customizations such as setting a title, labels, grid, tick parameters, annotation, and modifying spines.

#### **Plotly**

Next, let's create a similar plot using Plotly, which will allow for interactive customization:

import plotly.graph_objects as go
import numpy as np

# Generate some data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# Create the figure
fig = go.Figure()

# Add line trace
fig.add_trace(go.Scatter(x=x, y=y, mode='lines', name='Sine Wave', line=dict(color='blue', width=2)))

# Adding title and labels
fig.update_layout(
    title='Sine Wave Example',
    xaxis_title='X Axis',
    yaxis_title='Y Axis',
    title_font=dict(size=20),
    font=dict(size=14)
)

# Customize x-axis and y-axis
fig.update_xaxes(tickangle=45, tickfont=dict(size=12))
fig.update_yaxes(tickfont=dict(size=12))

# Annotating a point
fig.add_annotation(
    x=1.57,
    y=1,
    text="Peak",
    showarrow=True,
    arrowhead=1
)

# Add grid
fig.update_xaxes(showgrid=True, gridwidth=0.5, gridcolor='gray')
fig.update_yaxes(showgrid=True, gridwidth=0.5, gridcolor='gray')

# Customize theme
fig.update_layout(template='simple_white')

# Show the plot
fig.show()
This code also generates a sine wave plot and applies various customizations similar to the Matplotlib example. Notice how Plotly's `update_layout`, `update_xaxes`, and `update_yaxes` methods provide extensive options for modifications, and the resulting plot is interactive.

### Interactive Features

Interactivity is where Plotly excels, allowing for hover information, zooming, and panning by default.

#### Plotly Interactive Example

import plotly.express as px

df = px.data.gapminder().query("continent == 'Oceania'")
fig = px.line(df, x='year', y='gdpPercap', color='country', title='Interactive Plotly Line Plot')
fig.show()
Matplotlib can also create interactive plots, but requires additional libraries like `mpl_interactions` or enabling specific features in Jupyter notebooks.

### Static vs Interactive Use Cases

- **Matplotlib**: Ideal for static plots in scientific papers, reports, or presentations.
- **Plotly**: Best suited for interactive dashboards, web applications, and presentations where user interaction is essential.

### Conclusion and Recommendations

Both libraries are powerful tools for data visualization, but they cater to different needs:

- **Choose Matplotlib if**:
  - You need static, high-quality visualizations.
  - Extensive customization and control over plot elements are required.
  - You prefer a more traditional, script-based approach to plotting.

- **Choose Plotly if**:
  - You need interactive, dynamic visualizations.
  - You are building a web application or dashboard.
  - Quick, visually appealing plots with built-in interactivity are required.
  
Consider your project requirements and choose the library that best suits your needs. Additionally, you can leverage both libraries in a single project: use Matplotlib for static plots and Plotly for interactive dashboards.