How to save a histogram plot in Python?

When working with data visualization, plotting and saving a histogram on a local machine is a common task. This can be done using various functions provided by Python's Matplotlib, such as plt.savefig() and plt.hist().

The plt.hist() function is used to create a histogram by taking a list of data points. After the histogram is plotted, we can save it using the plt.savefig() function.

Basic Example

Here's a simple example that creates, saves, and displays a histogram ?

import matplotlib.pyplot as plt

# Sample data
data = [1, 3, 2, 5, 4, 7, 5, 1, 0, 4, 1]

# Create histogram
plt.hist(data, bins=8, color='skyblue', alpha=0.7)
plt.title('Sample Histogram')
plt.xlabel('Values')
plt.ylabel('Frequency')

# Save the histogram
plt.savefig('histogram.png', dpi=300, bbox_inches='tight')

# Display the plot
plt.show()

Customizing Figure Size and Layout

You can customize the figure size and layout before plotting to ensure your histogram looks good when saved ?

import matplotlib.pyplot as plt

# Configure figure size
plt.figure(figsize=(10, 6))

# Sample data
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 6, 6, 7]

# Create histogram with custom styling
plt.hist(data, bins=7, color='lightgreen', edgecolor='black', alpha=0.8)
plt.title('Customized Histogram', fontsize=16)
plt.xlabel('Data Values', fontsize=12)
plt.ylabel('Frequency', fontsize=12)
plt.grid(True, alpha=0.3)

# Save with high quality
plt.savefig('custom_histogram.png', dpi=300, bbox_inches='tight')
plt.show()

Saving in Different Formats

You can save histograms in various formats by specifying the file extension ?

import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
data = np.random.normal(50, 15, 1000)

# Create histogram
plt.figure(figsize=(8, 5))
plt.hist(data, bins=30, color='orange', alpha=0.7)
plt.title('Normal Distribution Histogram')
plt.xlabel('Values')
plt.ylabel('Frequency')

# Save in multiple formats
plt.savefig('histogram.png')    # PNG format
plt.savefig('histogram.pdf')    # PDF format
plt.savefig('histogram.svg')    # SVG format
plt.savefig('histogram.jpg', dpi=150)  # JPEG with custom DPI

plt.show()

Key savefig() Parameters

Parameter Description Example
dpi Resolution in dots per inch dpi=300
bbox_inches Bounding box in inches bbox_inches='tight'
facecolor Background color facecolor='white'
transparent Transparent background transparent=True

Complete Example with Error Handling

Here's a robust example that includes error handling for file operations ?

import matplotlib.pyplot as plt
import numpy as np

def save_histogram(data, filename='histogram.png'):
    try:
        # Create figure
        plt.figure(figsize=(10, 6))
        
        # Create histogram
        plt.hist(data, bins=20, color='steelblue', alpha=0.7, edgecolor='black')
        plt.title('Data Distribution', fontsize=14)
        plt.xlabel('Values', fontsize=12)
        plt.ylabel('Frequency', fontsize=12)
        plt.grid(True, alpha=0.3)
        
        # Save the plot
        plt.savefig(filename, dpi=300, bbox_inches='tight')
        print(f"Histogram saved as {filename}")
        
        # Show the plot
        plt.show()
        
    except Exception as e:
        print(f"Error saving histogram: {e}")

# Example usage
sample_data = np.random.normal(100, 20, 500)
save_histogram(sample_data, 'final_histogram.png')

Conclusion

Use plt.hist() to create histograms and plt.savefig() to save them in various formats. Configure figure size and use parameters like dpi=300 and bbox_inches='tight' for high-quality output.

Updated on: 2026-03-26T13:19:27+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements