6
Lesson 6
Bar charts and histograms
Objective
By the end of this lesson, students will learn how to create bar charts and histograms using Matplotlib, and how to adjust bar alignment and spacing for better visual representation.
1. Creating bar charts with bar():
Bar charts are used to represent categorical data with rectangular bars. The height of each bar is proportional to the value it represents.
Syntax:
By the end of this lesson, students will learn how to create bar charts and histograms using Matplotlib, and how to adjust bar alignment and spacing for better visual representation.
1. Creating bar charts with bar():
Bar charts are used to represent categorical data with rectangular bars. The height of each bar is proportional to the value it represents.
Syntax:
plt.bar(x, height, width, align)
- x : The x-coordinates of the bars.
- height : The heights of the bars.
- width : The width of the bars (optional).
- align : Alignment of the bars (optional).
Example:
import matplotlib.pyplot as plt # Sample data categories = ['A', 'B', 'C', 'D'] values = [4, 7, 1, 8] # Create a bar chart plt.bar(categories, values, color='blue', width=0.5) # Add title and labels plt.title('Bar Chart Example') plt.xlabel('Categories') plt.ylabel('Values') # Show the plot plt.show()
In this example:
- The bar() function creates a bar chart with categories on the x-axis and corresponding values as bar heights.
- The bars are colored blue, and titles and labels are added for clarity.
2. Creating histograms with hist():
Histograms are used to represent the distribution of a dataset. They group the data into bins and display the frequency of data points in each bin.
Syntax:
plt.hist(data, bins, color, alpha)
- data : The input data for which the histogram is to be created.
- bins : The number of bins or specific bin edges (optional).
- color : The color of the bars (optional).
- alpha : The transparency of the bars (optional).
Example:
import matplotlib.pyplot as plt import numpy as np # Generate random data data = np.random.randn(1000) # Create a histogram plt.hist(data, bins=30, color='green', alpha=0.7) # Add title and labels plt.title('Histogram Example') plt.xlabel('Value') plt.ylabel('Frequency') # Show the plot plt.show()
In this example:
- Random data is generated using NumPy, and a histogram is created to display the distribution of the data.
- The bins parameter specifies how many bins the data should be divided into, and alpha adjusts the transparency of the bars.
3. Adjusting bar alignment and spacing:
a. Adjusting bar alignment:
You can adjust the alignment of the bars in a bar chart by setting the align parameter to center or edge.
- Center alignment: Bars are centered on their x-coordinates.
- Edge alignment: Bars are aligned to the left edge of their x-coordinates.
Example:
import matplotlib.pyplot as plt # Sample data categories = ['A', 'B', 'C', 'D'] values = [4, 7, 1, 8] # Create a bar chart with center alignment plt.bar(categories, values, color='blue', width=0.5, align='center') plt.title('Center Aligned Bar Chart') plt.xlabel('Categories') plt.ylabel('Values') plt.show()
b. Adjusting bar spacing:
You can control the spacing between bars by adjusting the width parameter in the bar() function. A smaller width will increase the spacing, while a larger width will decrease it.
Example:
import matplotlib.pyplot as plt # Sample data categories = ['A', 'B', 'C', 'D'] values = [4, 7, 1, 8] # Create a bar chart with adjusted spacing plt.bar(categories, values, color='blue', width=0.3) # Reduced width plt.title('Bar Chart with Adjusted Spacing') plt.xlabel('Categories') plt.ylabel('Values') plt.show()
In this example, reducing the width of the bars creates more space between them.
4. Exercises:
Exercice: 1
1. Use the following data to create a bar chart:
Categories: ['Red', 'Blue', 'Green', 'Yellow']
Values: [5, 10, 15, 20]
2. Add titles and labels to the chart.
Exercice: 2
1. Generate random data using NumPy:
2. Use np.random.randn(500) to create 500 random numbers.
3. Create a histogram with 20 bins and adjust the color to orange.
Exercice: 3
1. Create a bar chart with the following data:
Categories: ['A', 'B', 'C', 'D', 'E']
Values: [8, 4, 7, 5, 9]
Use an edge alignment and a width of 0.4.
2. Add titles and labels to the chart.
Conclusion
In this lesson, we explored how to create bar charts and histograms using Matplotlib. We learned how to adjust bar alignment and spacing for improved visual representation of data. In the next lesson, we will delve into more advanced techniques for visualizing categorical and continuous data using Matplotlib.