Bar Chart in Plotly
Last Updated: 08 Nov 2025
Bar charts display categorical data with rectangular bars — perfect for comparisons, rankings, survey results, or sales by category.
Hinglish Tip: Bar chart = "kaun kitna hai" — jaise exam marks! Taller bar = zyada value.
Basic Bar Chart
import plotly.express as px
# Sample data
categories = ['Apple', 'Banana', 'Orange', 'Mango']
sales = [45, 30, 55, 40]
fig = px.bar(x=categories, y=sales, title="Fruit Sales")
fig.show()
Key Parameters in px.bar()
| Parameter | Values / Examples | Purpose |
|---|---|---|
| data_frame | df | Use Pandas DataFrame |
| x, y | Column names | Categories & values |
| color | Column name | Color bars by group |
| barmode | 'stack', 'group', 'overlay', 'relative' | How bars are placed |
| text | Column or 'auto' | Show values on bars |
| orientation | 'v' (vertical), 'h' (horizontal) | Flip to horizontal bar |
| hover_data | ['profit'] | Extra info on hover |
| title | String | Chart title |
| labels | 'y': 'Revenue' | Rename axes |
Full Example: Grouped & Stacked Bar (Sales by Region)
import plotly.express as px
import pandas as pd
# Sample data
df = pd.DataFrame({
'Month': ['Jan', 'Feb', 'Mar'] * 2,
'Sales': [30, 35, 40, 25, 30, 38],
'Region': ['North']*3 + ['South']*3,
'Product': ['A', 'B', 'C'] * 2
})
# Grouped Bar
fig1 = px.bar(
df, x='Month', y='Sales', color='Region',
barmode='group',
title='Sales by Region (Grouped)',
labels={'Sales': 'Revenue (₹K)'},
text='Sales',
height=500
)
fig1.update_traces(textposition='outside')
fig1.show()
# Stacked Bar
fig2 = px.bar(
df, x='Month', y='Sales', color='Region',
barmode='stack',
title='Sales by Region (Stacked)',
text='Sales',
hover_data=['Product']
)
fig2.update_traces(textposition='inside')
fig2.show()
Hinglish Tip: barmode='group' → side-by-side comparison, barmode='stack' → total dikhega + parts
Horizontal Bar Chart (orientation='h')
fig = px.bar(
df, x='Sales', y='Product', color='Region',
orientation='h',
title='Top Products by Sales (Horizontal)',
text='Sales',
color_discrete_sequence=px.colors.qualitative.Set2
)
fig.update_traces(textposition='outside')
fig.show()
Hinglish Tip: Horizontal bar → long category names ke liye best (no overlap!)
Add Value Labels + Custom Colors
fig = px.bar(
df, x='Month', y='Sales', color='Region',
barmode='stack',
text='Sales',
color_discrete_map={'North': '#1f77b4', 'South': '#ff7f0e'}
)
fig.update_traces(texttemplate='%{text}K', textposition='inside')
fig.update_layout(uniformtext_minsize=10, uniformtext_mode='hide')
fig.show()
Common Mistakes to Avoid
| Mistake | Fix |
|---|---|
| Text overlaps | Use textposition='outside' + uniformtext_mode |
| Too many colors → confusing | Use color_discrete_sequence=px.colors.qualitative.Pastel |
| Vertical labels unreadable | Use orientation='h' |
| Can't see small bars | Use barmode='stack' or log scale |
| No export | Install kaleido |