How to save a histogram plot in Python?

MatplotlibPythonData Visualization

To save a histogram plot in Python, we can take the following steps −

  • Set the figure size and adjust the padding between and around the subplots.
  • Create data points "k" for the histogram.
  • Plot the histogram using hist() method.
  • To save the histogram, use plt.savefig('image_name').
  • To display the figure, use show() method.

Example

import matplotlib.pyplot as plt

# Set the figure size
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Data points for the histogram
k = [1, 3, 2, 5, 4, 7, 5, 1, 0, 4, 1]

# Plot the histogram
plt.hist(k)

# Save the histogram
plt.savefig('hist.png')

# Display the plot
plt.show()

Output

It will save the following plot as 'hist.png' in the project directory.

raja
Updated on 21-Sep-2021 11:13:15

Advertisements