In this Matplotlib tutorial we want to learn about Matplotlib Histogram, so Matplotlib, histograms are powerful tool in data visualization, and it allows us to analyze the distribution and frequency of values within a dataset. Python Matplotlib library provides simple and effective way to create histograms.
For creating histogram, we need to import the required modules.
1 2 |
import matplotlib.pyplot as plt import numpy as np |
For creating of histogram, we need to generate some random data using numpy random.randn() function. This will give us an array of random numbers with a normal distribution.
1 |
data = np.random.randn(1000) |
Using Matplotlib hist() function, we can create a histogram based on the generated data.
1 |
plt.hist(data, bins=30, color='skyblue', edgecolor='black') |
Matplotlib provides different customization options to enhance the appearance. You can add labels, change colors, adjust the bin size and many more.
1 2 3 |
plt.xlabel('Values') plt.ylabel('Frequency') plt.title('Histogram') |
For displaying the histogram, we can use the plt.show() function.
1 |
plt.show() |
If you wish to save the histogram as an image, you can use the plt.savefig() function instead.
1 |
plt.savefig('histogram.png') |
This is the complete code for this article
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import matplotlib.pyplot as plt import numpy as np # Generate Sample Data data = np.random.randn(1000) # Create the Histogram plt.hist(data, bins=30, color='skyblue', edgecolor='black') # Customize the Histogram plt.xlabel('Values') plt.ylabel('Frequency') plt.title('Histogram') # Display the Histogram plt.show() # Save the Histogram as an Image # plt.savefig('histogram.png') |
Run your code and this will be the output
Learn More on Python Matplotlib
- Learn Python Matplotlib
- Data Visualization in Matplotlib
- How to Create Plotting Styles in Matplotlib
- How to Create Time Series in Matplotlib
- How to Customize Matplotlib Graphs
- How to Create Interactive Plots in Matplotlib
Subscribe and Get Free Video Courses & Articles in your Email