简体   繁体   中英

Save specific part of matplotlib figure

I want to save only a specific part of a matplotlib figure by giving coordinates of a rectangle. The below code creates and saves the whole figure:

import numpy as np
import matplotlib.pyplot as plt

# Fixing random state for reproducibility
np.random.seed(19680801)

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30 * np.random.rand(N))**2
plt.scatter(x, y, s=area, c=colors, alpha=0.5)

plt.savefig('Plot.png', format='png')

I want to save only a specific part inside the plot determined by 4 points (in data coordinates), for example only the highlighted rectangular area:

Desired result: Save only the part highlighted in green

You can use the parameter bbox_inches= of savefig() to delimit the region to save. The problem is finding out the coordinates of the region in inches. For that, you have to use transforms :

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.transforms import Bbox

# Fixing random state for reproducibility
np.random.seed(19680801)

N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = (30 * np.random.rand(N))**2

fig, ax = plt.subplots()
ax.scatter(x, y, s=area, c=colors, alpha=0.5)
fig.canvas.draw()  # force draw

x0,x1 = 0.2, 0.6
y0,y1 = 0.4, 0.8

bbox = Bbox([[x0,y0],[x1,y1]])
bbox = bbox.transformed(ax.transData).transformed(fig.dpi_scale_trans.inverted())
fig.savefig('test.png', bbox_inches=bbox)

在此处输入图片说明

test.png

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM