Creating Interactive Line and Bar Charts
Line and bar charts are commonly used in business analysis. Plotly makes both interactive, allowing users to inspect values and compare categories.
Interactive Line Charts
Line charts help reveal changes over time or across an ordered sequence.
import pandas as pd
import plotly.express as px
df = pd.DataFrame({
"Month": ["Jan", "Feb", "Mar", "Apr", "May", "Jun"],
"Sales": [15000, 18000, 16000, 22000, 25000, 28000]
})
fig = px.line(
df,
x="Month",
y="Sales",
title="Monthly Sales Performance",
markers=True,
labels={
"Month": "Month",
"Sales": "Sales Revenue"
}
)
fig.show()
The markers=True option displays individual observations. Hovering over a point reveals its associated values.
Comparing Multiple Categories
You can use the color parameter to display multiple categories in the same chart.
df = pd.DataFrame({
"Month": ["Jan", "Feb", "Mar", "Jan", "Feb", "Mar"],
"Region": ["North", "North", "North", "South", "South", "South"],
"Sales": [12000, 15000, 17000, 10000, 14000, 16000]
})
fig = px.line(
df,
x="Month",
y="Sales",
color="Region",
markers=True,
title="Regional Sales Comparison"
)
fig.show()
Separate lines make it easier to compare regional trends. For meaningful comparisons, ensure the time periods and measurement units are consistent.
Interactive Bar Charts
Bar charts are useful for comparing numerical values across categories.
df = pd.DataFrame({
"Product": ["Laptop", "Phone", "Tablet"],
"Units_Sold": [120, 250, 180]
})
fig = px.bar(
df,
x="Product",
y="Units_Sold",
title="Product Sales Comparison",
color="Product",
text="Units_Sold"
)
fig.show()
The text parameter displays values on the bars, while color distinguishes product categories. Users can hover over bars for additional information.
Python for Data Science
Vishalini A








