๐ Plotly Interactive Visualizations for Data Scientists
Plotly makes your charts interactive, dynamic, and stunningly modern — all with just a few lines of Python.
Zoom, hover, and explore your data like never before!
This post shows the most useful examples using plotly.express.
1️⃣ Install & Import Plotly
# Install Plotly (if not already installed)
!pip install plotly
import plotly.express as px
import pandas as pd
2️⃣ Line Chart — Trend Over Time
# Sample DataFrame
df = pd.DataFrame({
'Month': ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'],
'Sales': [200, 250, 300, 400, 450, 500]
})
# Interactive Line Chart
fig = px.line(df, x='Month', y='Sales', title='Monthly Sales Trend', markers=True)
fig.show()
3️⃣ Bar Chart — Comparing Categories
df = pd.DataFrame({
'Product': ['A', 'B', 'C', 'D'],
'Revenue': [1200, 900, 1500, 1100]
})
fig = px.bar(df, x='Product', y='Revenue', color='Product',
title='Revenue by Product', text='Revenue')
fig.update_traces(textposition='outside')
fig.show()
4️⃣ Scatter Plot — Data Relationship
# Built-in dataset
df = px.data.iris()
# Interactive scatter with hover info
fig = px.scatter(df, x='sepal_width', y='sepal_length',
color='species', size='petal_length',
hover_data=['petal_width'],
title='Iris Flower Data')
fig.show()
5️⃣ Pie Chart — Category Proportions
fig = px.pie(df, names='species', title='Iris Species Distribution', hole=0.3)
fig.show()
6️⃣ Box Plot — Distribution Analysis
fig = px.box(df, x='species', y='sepal_length', color='species',
title='Sepal Length Distribution by Species')
fig.show()
7️⃣ Histogram — Frequency Distribution
fig = px.histogram(df, x='petal_length', nbins=20, color='species',
title='Petal Length Distribution')
fig.show()
8️⃣ Heatmap — Correlation Matrix
corr = df.corr(numeric_only=True)
fig = px.imshow(corr, text_auto=True, color_continuous_scale='viridis',
title='Correlation Heatmap')
fig.show()
9️⃣ Geo Visualization — World Map
geo_df = px.data.gapminder().query("year == 2007")
fig = px.choropleth(
geo_df,
locations="iso_alpha",
color="lifeExp",
hover_name="country",
title="๐ Life Expectancy Around the World (2007)",
color_continuous_scale=px.colors.sequential.Plasma
)
fig.show()
๐ Animated Chart — Population Growth Over Time
gapminder = px.data.gapminder()
fig = px.scatter(
gapminder,
x="gdpPercap",
y="lifeExp",
animation_frame="year",
animation_group="country",
size="pop",
color="continent",
hover_name="country",
log_x=True,
size_max=55,
range_x=[100,100000],
range_y=[25,90],
title="๐ Population Growth (1952–2007)"
)
fig.show()
๐ก Pro Tip: Use fig.write_html("chart.html") to save any Plotly chart as an interactive web page!
Perfect for dashboards, portfolios, or blog embeds. ๐
No comments:
Post a Comment