Để lưu figure thành PDF dạng raster images trong Matplotlib:
- Thiết lập kích thước hình và điều chỉnh khoảng đệm subplot.
- Tạo figure mới.
- Thêm axes vào figure như subplot arrangement.
- Tạo dữ liệu ngẫu nhiên bằng numpy.
- Hiển thị dữ liệu như hình ảnh 2D raster.
- Lưu plot dạng pdf.
Ví dụ
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot(111, rasterized=True)
data = np.random.rand(5, 5)
ax.imshow(data, cmap="copper", aspect=True, interpolation="nearest")
plt.savefig("rasterized.pdf")
Kết quả
Khi chạy mã, biểu đồ sẽ được lưu trong thư mục dự án tên "rasterized.pdf".
