~/snippets/DataVisualizationWithPlotly
Published on

Data Visualization with Plotly

697 words4 min read–––
Views

Quick examples for creating interactive visualizations with Plotly Express:

import plotly.express as px
import pandas as pd
import numpy as np

# Sample data
df = px.data.gapminder().query("year == 2007")
stocks = pd.DataFrame({
    'date': pd.date_range(start='2020-01-01', periods=100),
    'stock_a': np.cumsum(np.random.randn(100)) + 100,
    'stock_b': np.cumsum(np.random.randn(100)) + 100,
    'stock_c': np.cumsum(np.random.randn(100)) + 100
})
stocks_melted = stocks.melt(id_vars=['date'], value_vars=['stock_a', 'stock_b', 'stock_c'], 
                            var_name='stock', value_name='price')

# 1. Scatter plot with bubble size and color
fig = px.scatter(
    df, 
    x="gdpPercap", 
    y="lifeExp", 
    size="pop", 
    color="continent",
    hover_name="country", 
    log_x=True, 
    size_max=60,
    title="GDP per Capita vs Life Expectancy (2007)"
)
fig.show()

# 2. Line chart for time series data
fig = px.line(
    stocks_melted, 
    x='date', 
    y='price', 
    color='stock',
    title='Stock Price Over Time'
)
fig.show()

# 3. Bar chart
fig = px.bar(
    df, 
    x='continent', 
    y='pop', 
    color='continent',
    title='Population by Continent (2007)'
)
fig.show()

# 4. Histogram
fig = px.histogram(
    df, 
    x="lifeExp", 
    color="continent",
    marginal="box",  # can be 'box', 'violin', 'rug'
    title="Life Expectancy Distribution by Continent"
)
fig.show()

# 5. Box plot
fig = px.box(
    df, 
    x="continent", 
    y="lifeExp", 
    color="continent",
    title="Life Expectancy by Continent"
)
fig.show()

# 6. Heatmap for correlation matrix
correlation = df.select_dtypes('number').corr()
fig = px.imshow(
    correlation,
    text_auto=True,
    color_continuous_scale='RdBu_r',
    title="Correlation Matrix of Numerical Features"
)
fig.show()

# 7. Choropleth map
fig = px.choropleth(
    df, 
    locations="iso_alpha",
    color="lifeExp", 
    hover_name="country", 
    projection="natural earth",
    title="Life Expectancy Around the World (2007)"
)
fig.show()

# Save any visualization to HTML for sharing
# fig.write_html("visualization.html")

Installation:

pip install plotly pandas numpy

Plotly Express provides a simple, high-level interface for creating interactive visualizations in Python. The resulting charts can be embedded in web applications or dashboards, allowing for rich interactivity including zooming, panning, and tooltips.