DEV Community

Cover image for How to Export Matplotlib Plots to JPEG or PDF
Lohith
Lohith

Posted on

How to Export Matplotlib Plots to JPEG or PDF

To save a plot created using Matplotlib to a JPEG or PDF file, you can follow these steps:

  1. First, create your plot using Matplotlib. For example, let's say you have a simple line plot:

    import matplotlib.pyplot as plt
    import numpy as np
    
    # Generate some example data
    x = np.linspace(0, 10, 100)
    y = np.sin(x)
    
    # Create the plot
    plt.plot(x, y)
    plt.xlabel('X-axis')
    plt.ylabel('Y-axis')
    plt.title('Sine Wave')
    
    # Show the plot (optional)
    plt.show()
    

    Figure 1

2.After creating the plot, you can save it to a file using the savefig function. Specify the filename and the desired format (JPEG or PDF). For example:

```python
# Save the plot as a JPEG file
plt.savefig('my_plot.jpg', format='jpeg')

# Save the plot as a PDF file
plt.savefig('my_plot.pdf', format='pdf')
```
Enter fullscreen mode Exit fullscreen mode

Replace 'my_plot.jpg' and 'my_plot.pdf' with your desired filenames.

3.The saved file will be in the same directory where your Python script is located.

Remember to adjust the plot and filenames according to your specific use case. If you have any other questions or need further assistance, feel free to ask! 😊

Top comments (0)