Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to change the default path for "save the figure" in Matplotlib?
To change the default path for "save the figure" in Matplotlib, you can use rcParams["savefig.directory"] to set the directory path. This allows you to specify where figures are saved by default without providing the full path each time.
Setting Default Save Directory
The most straightforward approach is to set the rcParams directory directly ?
import matplotlib.pyplot as plt
import numpy as np
import os
# Set default save directory
plt.rcParams["savefig.directory"] = "/tmp"
# Create sample data and plot
data = np.random.rand(5, 5)
plt.figure(figsize=(6, 4))
plt.imshow(data, cmap="viridis")
plt.title("Sample Heatmap")
plt.colorbar()
# This will save to the default directory set above
plt.savefig("sample_plot.png")
plt.show()
Using os.chdir() Method
You can also change the working directory, which affects where files are saved ?
import matplotlib.pyplot as plt
import numpy as np
import os
# Change working directory
original_dir = os.getcwd()
new_dir = "/tmp"
try:
os.chdir(new_dir)
# Create and save plot
data = np.random.rand(4, 4)
plt.figure(figsize=(5, 4))
plt.imshow(data, cmap="plasma")
plt.title("Changed Directory Example")
plt.savefig("plot_in_new_dir.png")
plt.show()
finally:
# Restore original directory
os.chdir(original_dir)
Specifying Full Path
For more control, you can specify the complete file path in savefig() ?
import matplotlib.pyplot as plt
import numpy as np
import os
# Create sample plot
data = np.random.rand(3, 3)
plt.figure(figsize=(5, 4))
plt.imshow(data, cmap="coolwarm")
plt.title("Full Path Example")
# Save with full path specification
save_path = os.path.join("/tmp", "custom_plot.png")
plt.savefig(save_path)
plt.show()
print(f"Plot saved to: {save_path}")
Plot saved to: /tmp/custom_plot.png
Comparison of Methods
| Method | Scope | Best For |
|---|---|---|
rcParams["savefig.directory"] |
All subsequent plots | Setting global default |
os.chdir() |
All file operations | Temporary directory change |
Full path in savefig()
|
Single plot only | Precise control per plot |
Conclusion
Use rcParams["savefig.directory"] to set a global default save directory for all plots. For individual plots, specify the full path directly in savefig() for maximum control.
Advertisements
