Python 如何更改使用Matplotlib绘制的地物的大小?
如何更改使用Matplotlib绘制的地物的大小 弃用说明:Python 如何更改使用Matplotlib绘制的地物的大小?,python,graph,matplotlib,plot,visualization,Python,Graph,Matplotlib,Plot,Visualization,如何更改使用Matplotlib绘制的地物的大小 弃用说明: 根据,不再建议使用pylab模块。请考虑使用 MatPultLIB。PyPrPux/Cult>模块,如所描述的。 以下似乎有效: from pylab import rcParams rcParams['figure.figsize'] = 5, 10 这使得图形的宽度为5英寸,高度为10英寸 然后,Figure类将此作为其参数之一的默认值。Google中“matplotlib Figure size”的第一个链接是() 这是上一页
根据,不再建议使用
pylab
模块。请考虑使用<代码> MatPultLIB。PyPrPux/Cult>模块,如所描述的。
以下似乎有效:
from pylab import rcParams
rcParams['figure.figsize'] = 5, 10
这使得图形的宽度为5英寸,高度为10英寸
然后,Figure类将此作为其参数之一的默认值。Google中“matplotlib Figure size”的第一个链接是() 这是上一页的测试脚本。它创建同一图像的不同大小的
test[1-3].png
文件:
#!/usr/bin/env python
"""
This is a small demo file that helps teach how to adjust figure sizes
for matplotlib
"""
import matplotlib
print "using MPL version:", matplotlib.__version__
matplotlib.use("WXAgg") # do this before pylab so you don'tget the default back end.
import pylab
import numpy as np
# Generate and plot some simple data:
x = np.arange(0, 2*np.pi, 0.1)
y = np.sin(x)
pylab.plot(x,y)
F = pylab.gcf()
# Now check everything with the defaults:
DPI = F.get_dpi()
print "DPI:", DPI
DefaultSize = F.get_size_inches()
print "Default size in Inches", DefaultSize
print "Which should result in a %i x %i Image"%(DPI*DefaultSize[0], DPI*DefaultSize[1])
# the default is 100dpi for savefig:
F.savefig("test1.png")
# this gives me a 797 x 566 pixel image, which is about 100 DPI
# Now make the image twice as big, while keeping the fonts and all the
# same size
F.set_size_inches( (DefaultSize[0]*2, DefaultSize[1]*2) )
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test2.png")
# this results in a 1595x1132 image
# Now make the image twice as big, making all the fonts and lines
# bigger too.
F.set_size_inches( DefaultSize )# resetthe size
Size = F.get_size_inches()
print "Size in Inches", Size
F.savefig("test3.png", dpi = (200)) # change the dpi
# this also results in a 1595x1132 image, but the fonts are larger.
输出:
using MPL version: 0.98.1
DPI: 80
Default size in Inches [ 8. 6.]
Which should result in a 640 x 480 Image
Size in Inches [ 16. 12.]
Size in Inches [ 16. 12.]
注二:
from matplotlib.pyplot import figure
figure(figsize=(8, 6), dpi=80)
figure(figsize=(1,1))
将创建一个逐英寸图像,该图像将为80×80像素,除非您还提供不同的dpi参数。如果您已经创建了该图形,您可以快速执行以下操作:
fig = matplotlib.pyplot.gcf()
fig.set_size_inches(18.5, 10.5)
fig.savefig('test2png.png', dpi=100)
要将大小更改传播到现有GUI窗口,请添加forward=True
:
fig.set_size_inches(18.5, 10.5, forward=True)
尝试注释掉
fig=…
行
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2
fig = plt.figure(figsize=(18, 18))
plt.scatter(x, y, s=area, alpha=0.5)
plt.show()
这对我来说很有效:
从matplotlib导入pyplot作为plt
F=plt.gcf()
尺寸=F。获得尺寸英寸()
F.设置_size_inches(大小[0]*2,大小[1]*2,正向=真)#设置forward为真以调整窗口大小以及图中的绘图。
plt.show()#或plt.imshow(z_数组),如果使用动画,其中z_数组是矩阵或NumPy数组
此论坛帖子也可能有帮助:请尝试以下简单代码:
from matplotlib import pyplot as plt
plt.figure(figsize=(1,1))
x = [1,2,3]
plt.plot(x, x)
plt.show()
import matplotlib
matplotlib.rc('figure', figsize=(10, 5))
打印前需要设置地物大小。即使在绘制地物之后,也会立即调整地物的大小(至少使用Qt4Agg/TkAgg,但不使用Mac OS X和Matplotlib 1.4.0):
要将地物的大小增加N倍,需要在pl.show()之前插入此项: 它也适用于笔记本电脑。由于Matplotlib本机使用公制,如果您想以合理的长度单位(如厘米)指定图形大小,可以执行以下操作(代码来自): 然后您可以使用:
plt.figure(figsize=cm2inch(21, 29.7))
如果您正在寻找一种方法来更改熊猫中的体型大小,例如,您可以:
df['some_column'].plot(figsize=(10, 5))
其中,df
是一个数据帧。或者,要使用现有图形或轴:
fig, ax = plt.subplots(figsize=(10, 5))
df['some_column'].plot(ax=ax)
如果要更改默认设置,可以执行以下操作:
from matplotlib import pyplot as plt
plt.figure(figsize=(1,1))
x = [1,2,3]
plt.plot(x, x)
plt.show()
import matplotlib
matplotlib.rc('figure', figsize=(10, 5))
使用plt.rcParams
如果您希望在不使用体形环境的情况下更改尺寸,也有此解决方法。所以,如果您使用的是例如,您可以设置一个具有宽度和高度的元组
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (20,3)
这在内联打印时非常有用(例如,使用)。因此,最好不要将此语句放在imports语句的同一单元格中
要将后续绘图的全局地物大小重置回默认值,请执行以下操作:
plt.rcParams["figure.figsize"] = plt.rcParamsDefault["figure.figsize"]
转换为厘米
figsize
元组接受英寸,因此如果要将其设置为厘米,则必须将其除以2.54。查看。您可以简单地使用(从):
从Matplotlib 2.0.0开始,画布上的更改将立即可见,如forward
关键字
如果你想两者兼而有之,你可以使用
fig.set\u figwidth(val)
或fig.set\u figheight(val)
这些也将立即更新画布,但仅限于Matplotlib 2.2.0及更新版本
对于旧版本
您需要明确指定
forward=True
,以便在比上面指定的版本旧的版本中实时更新画布。请注意,set\u figwidth
和set\u fighight
函数在早于Matplotlib 1.5.0的版本中不支持forward
参数。另一个选项是在Matplotlib中使用rc()函数(单位为英寸):
您还可以使用:
fig, ax = plt.subplots(figsize=(20, 10))
概括和简化: 如果要按系数
sizefactor
更改地物的当前大小:
import matplotlib.pyplot as plt
# Here goes your code
fig_size = plt.gcf().get_size_inches() # Get current size
sizefactor = 0.8 # Set a zoom factor
# Modify the current size by the factor
plt.gcf().set_size_inches(sizefactor * fig_size)
更改当前大小后,可能需要微调子地块布局。您可以在图形窗口GUI中或通过命令执行此操作
比如说,
plt.subplots_adjust(left=0.16, bottom=0.19, top=0.82)
我总是使用以下模式:
x_inches = 150*(1/25.4) # [mm]*constant
y_inches = x_inches*(0.8)
dpi = 96
fig = plt.figure(1, figsize = (x_inches,y_inches), dpi = dpi, constrained_layout = True)
通过此示例,您可以以英寸或毫米为单位设置地物尺寸。将
constrated\u layout
设置为True
时,打印会无边框地填充您的图形。比较不同方法以设置精确的图像大小(以像素为单位)
这个答案将集中于:
savefig
- 以像素为单位设置大小
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
fig, ax = plt.subplots()
print('fig.dpi = {}'.format(fig.dpi))
print('fig.get_size_inches() = ' + str(fig.get_size_inches())
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig('base.png', format='png')
运行:
产出:
fig.dpi = 100.0
fig.get_size_inches() = [6.4 4.8]
base.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000
get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000
main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000
magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000
magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000
set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000
set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000
我目前为止的最佳方法:plt.savefig(dpi=h/fig.get_size_inches()[1]
仅限高度控制
我想这是我大部分时间都会用到的,因为它很简单,而且可以缩放:
获取_size.py
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'get_size.png',
format='png',
dpi=height/fig.get_size_inches()[1]
)
运行:
产出:
fig.dpi = 100.0
fig.get_size_inches() = [6.4 4.8]
base.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000
get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000
main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000
magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000
magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000
set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000
set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000
及
产出:
fig.dpi = 100.0
fig.get_size_inches() = [6.4 4.8]
base.png PNG 640x480 640x480+0+0 8-bit sRGB 13064B 0.000u 0:00.000
get_size.png PNG 574x431 574x431+0+0 8-bit sRGB 10058B 0.000u 0:00.000
main.png PNG 1724x1293 1724x1293+0+0 8-bit sRGB 46709B 0.000u 0:00.000
magic.png PNG 431x231 431x231+0+0 8-bit sRGB 7923B 0.000u 0:00.000
magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000
set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000
set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000
我倾向于只设定高度,因为我通常最关心的是,在我的正文中,图像将占据多少垂直空间。
plt.savefig(bbox\u inches='tight'
更改图像大小
我总是觉得图像周围有太多的空白,并且倾向于从以下位置添加bbox\u inches='tight'
:
但是,这是通过裁剪图像来实现的,您将无法获得所需的大小
取而代之的是,在
./magic.py 1291 693
magic.png PNG 1291x693 1291x693+0+0 8-bit sRGB 25013B 0.000u 0:00.000
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
w = int(sys.argv[1])
h = int(sys.argv[2])
fig, ax = plt.subplots()
fig.set_size_inches(w/fig.dpi, h/fig.dpi)
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(
0,
60.,
'Hello',
# Keep font size fixed independently of DPI.
# https://stackoverflow.com/questions/39395616/matplotlib-change-figsize-but-keep-fontsize-constant
fontdict=dict(size=10*h/fig.dpi),
)
plt.savefig(
'set_size_inches.png',
format='png',
)
./set_size_inches.py 431 231
set_size_inches.png PNG 430x231 430x231+0+0 8-bit sRGB 8078B 0.000u 0:00.000
./set_size_inches.py 1291 693
set_size_inches.png PNG 1291x693 1291x693+0+0 8-bit sRGB 19798B 0.000u 0:00.000
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
height = int(sys.argv[1])
fig, ax = plt.subplots()
t = np.arange(-10., 10., 1.)
plt.plot(t, t, '.')
plt.plot(t, t**2, '.')
ax.text(0., 60., 'Hello', fontdict=dict(size=25))
plt.savefig(
'get_size_svg.svg',
format='svg',
dpi=height/fig.get_size_inches()[1]
)
./get_size_svg.py 431
<svg height="345.6pt" version="1.1" viewBox="0 0 460.8 345.6" width="460.8pt"
get_size_svg.svg SVG 614x461 614x461+0+0 8-bit sRGB 17094B 0.000u 0:00.000
inkscape -h 431 get_size_svg.svg -b FFF -e get_size_svg.png
plt.figure(figsize=(width,height))
import matplotlib.pyplot as plt
plt.figure(figsize=(20,10))
plt.plot(x,y) ## This is your plot
plt.show()
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
figure(figsize=(16, 8), dpi=80)
plt.plot(x_test, color = 'red', label = 'Predicted Price')
plt.plot(y_test, color = 'blue', label = 'Actual Price')
plt.title('Dollar to PKR Prediction')
plt.xlabel('Predicted Price')
plt.ylabel('Actual Dollar Price')
plt.legend()
plt.show()