DEV Community

Cover image for Mastering Matplotlib: A Guide to Bar Charts, Histograms, Scatter Plots, and Pie Charts
Lohith
Lohith

Posted on

Mastering Matplotlib: A Guide to Bar Charts, Histograms, Scatter Plots, and Pie Charts

Let's dive into the different types of plots you can create using Matplotlib, along with examples:

  1. Bar Chart:

    • A bar chart (or bar plot) displays categorical data with rectangular bars. Each bar represents a category, and the height of the bar corresponds to the value of that category.
    • Example:
     import matplotlib.pyplot as plt
    
     x = [1, 3, 5, 7, 9]
     y1 = [5, 2, 7, 8, 2]
     y2 = [8, 6, 2, 5, 6]
    
     plt.bar(x, y1, label="Example one")
     plt.bar(x, y2, label="Example two", color='g')
    
     plt.xlabel("X-axis")
     plt.ylabel("Y-axis")
     plt.title("Bar Chart Example")
     plt.legend()
     plt.show()
    

Figure 1

  • This code creates a bar chart with two sets of bars, labeled "Example one" and "Example two" ⁴.

2.Histogram:

  • A histogram represents the distribution of continuous data by dividing it into bins and showing the frequency of values falling into each bin.
  • Example:

     import matplotlib.pyplot as plt
     import numpy as np
    
     data = np.random.randn(1000)  # Generate random data
     plt.hist(data, bins=20, edgecolor='black')
    
     plt.xlabel("Value")
     plt.ylabel("Frequency")
     plt.title("Histogram Example")
     plt.show()
    

Figure 2

  • This code creates a histogram from random data.

3.Scatter Plot:

  • A scatter plot displays individual data points as dots. It is useful for visualizing relationships between two continuous variables.
  • Example:

     import matplotlib.pyplot as plt
    
     x = [10, 20, 30, 40]
     y = [20, 25, 35, 55]
    
     plt.scatter(x, y, marker='o', color='b', label="Data points")
     plt.xlabel("X-axis")
     plt.ylabel("Y-axis")
     plt.title("Scatter Plot Example")
     plt.legend()
     plt.show()
    

Figure 3

  • This code creates a scatter plot with data points.

4.Pie Chart:

  • A pie chart represents parts of a whole. It shows the proportion of each category relative to the total.
  • Example:

     import matplotlib.pyplot as plt
    
     labels = ['Apples', 'Bananas', 'Cherries', 'Dates']
     sizes = [30, 25, 20, 15]
    
     plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
     plt.axis('equal')  # Equal aspect ratio ensures a circular pie chart
     plt.title("Pie Chart Example")
     plt.show()
    

Figure 4

  • This code creates a simple pie chart with labeled slices Β².

Remember to customize these plots further by adjusting labels, colors, and other parameters according to your specific requirements. Happy plotting! πŸ˜ŠπŸ“ŠπŸŽ¨

Top comments (0)