Display percentage above bar chart in Matplotlib

Display percentage above bar chart in Matplotlib

Displaying percentages above bars in a bar chart can make your plots more informative. Here's how you can display percentages above bars in a bar chart using matplotlib:

  1. First, ensure you have matplotlib installed:

    pip install matplotlib 
  2. Create a bar chart and display percentages above the bars:

import matplotlib.pyplot as plt # Sample data categories = ['A', 'B', 'C', 'D'] values = [50, 30, 70, 40] total = sum(values) percentages = [(value / total) * 100 for value in values] # Create a bar chart bars = plt.bar(categories, values, color=['blue', 'red', 'green', 'yellow']) # Display percentages above bars for bar, percentage in zip(bars, percentages): plt.text(bar.get_x() + bar.get_width() / 2 - 0.1, bar.get_height() + 2, f'{percentage:.1f}%', ha='center', va='center') plt.xlabel('Category') plt.ylabel('Value') plt.title('Bar chart with percentages') plt.show() 

In this example:

  • We first compute the percentages for each bar.
  • We then loop through each bar and use plt.text() to display the percentage above each bar.
  • Adjustments may be needed in the plt.text() parameters (especially the positioning parameters) based on your specific data and preferences.

More Tags

react-state-management create-table anonymous-types heidisql logfiles python-requests network-interface autowired kivy-language import-from-excel

More Programming Guides

Other Guides

More Programming Examples