Barchart with vertical labels in Python/Matplotlib

When creating bar charts in Python using Matplotlib, you can rotate axis labels to improve readability, especially when dealing with long label names. The xticks() function with the rotation parameter allows you to set labels vertically or at any angle.

Basic Bar Chart with Vertical Labels

Here's how to create a bar chart with vertical x-axis labels ?

from matplotlib import pyplot as plt

bars_heights = [14, 8, 10]
bars_label = ["A label", "B label", "C label"]

plt.bar(range(len(bars_label)), bars_heights)
plt.xticks(range(len(bars_label)), bars_label, rotation='vertical')
plt.show()

Different Rotation Angles

You can specify custom angles for label rotation ?

import matplotlib.pyplot as plt

categories = ['Category A', 'Category B', 'Category C', 'Category D']
values = [20, 35, 30, 25]

# Create subplots for different rotation angles
fig, axes = plt.subplots(2, 2, figsize=(12, 8))

# Vertical (90 degrees)
axes[0, 0].bar(categories, values)
axes[0, 0].set_title('Vertical (90°)')
axes[0, 0].tick_params(axis='x', rotation=90)

# Diagonal (45 degrees)
axes[0, 1].bar(categories, values)
axes[0, 1].set_title('Diagonal (45°)')
axes[0, 1].tick_params(axis='x', rotation=45)

# Horizontal (0 degrees)
axes[1, 0].bar(categories, values)
axes[1, 0].set_title('Horizontal (0°)')
axes[1, 0].tick_params(axis='x', rotation=0)

# Custom angle (30 degrees)
axes[1, 1].bar(categories, values)
axes[1, 1].set_title('Custom (30°)')
axes[1, 1].tick_params(axis='x', rotation=30)

plt.tight_layout()
plt.show()

Improved Formatting with Longer Labels

For longer labels, vertical rotation with proper spacing improves readability ?

import matplotlib.pyplot as plt

# Data with longer labels
products = ['Smartphone Sales', 'Laptop Revenue', 'Tablet Income', 'Smartwatch Profit']
quarterly_data = [45000, 32000, 18000, 12000]

plt.figure(figsize=(10, 6))
bars = plt.bar(products, quarterly_data, color=['#ff9999', '#66b3ff', '#99ff99', '#ffcc99'])

# Rotate labels and add formatting
plt.xticks(rotation='vertical')
plt.ylabel('Revenue ($)')
plt.title('Quarterly Product Revenue')

# Add value labels on top of bars
for bar, value in zip(bars, quarterly_data):
    plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 500, 
             f'${value:,}', ha='center', va='bottom')

plt.tight_layout()  # Prevents label cutoff
plt.show()

Key Parameters

Parameter Values Description
rotation 'vertical', 'horizontal', or angle (0-360) Sets the rotation angle for labels
ha 'left', 'center', 'right' Horizontal alignment of labels
va 'top', 'center', 'bottom' Vertical alignment of labels

Conclusion

Use rotation='vertical' in plt.xticks() for vertical labels or specify custom angles. Always use plt.tight_layout() to prevent label cutoff when rotating text.

Updated on: 2026-03-25T18:05:55+05:30

10K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements