如何最大化 plt.show() 窗口
- 2025-02-24 09:29:00
- admin 原创
- 66
问题描述:
出于好奇,我想知道如何在下面的代码中做到这一点。我一直在寻找答案,但毫无用处。
import numpy as np
import matplotlib.pyplot as plt
data=np.random.exponential(scale=180, size=10000)
print ('el valor medio de la distribucion exponencial es: ')
print np.average(data)
plt.hist(data,bins=len(data)**0.5,normed=True, cumulative=True, facecolor='red', label='datos tamano paqutes acumulativa', alpha=0.5)
plt.legend()
plt.xlabel('algo')
plt.ylabel('algo')
plt.grid()
plt.show()
解决方案 1:
我在 Windows(WIN7)上,运行 Python 2.7.5 和 Matplotlib 1.3.1。
我能够使用以下几行来最大化 TkAgg、QT4Agg 和 wxAgg 的图形窗口:
from matplotlib import pyplot as plt
### for 'TkAgg' backend
plt.figure(1)
plt.switch_backend('TkAgg') #TkAgg (instead Qt4Agg)
print '#1 Backend:',plt.get_backend()
plt.plot([1,2,6,4])
mng = plt.get_current_fig_manager()
### works on Ubuntu??? >> did NOT working on windows
# mng.resize(*mng.window.maxsize())
mng.window.state('zoomed') #works fine on Windows!
plt.show() #close the figure to run the next section
### for 'wxAgg' backend
plt.figure(2)
plt.switch_backend('wxAgg')
print '#2 Backend:',plt.get_backend()
plt.plot([1,2,6,4])
mng = plt.get_current_fig_manager()
mng.frame.Maximize(True)
plt.show() #close the figure to run the next section
### for 'Qt4Agg' backend
plt.figure(3)
plt.switch_backend('QT4Agg') #default on my system
print '#3 Backend:',plt.get_backend()
plt.plot([1,2,6,4])
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
plt.show()
如果你想最大化多个数字,你可以使用
for fig in figs:
mng = fig.canvas.manager
# ...
希望这个对先前答案(以及一些补充)的总结(结合一个工作示例(至少对于 Windows 而言))能够有所帮助。
解决方案 2:
使用 Qt 后端(FigureManagerQT)的正确命令是:
figManager = plt.get_current_fig_manager()
figManager.window.showMaximized()
解决方案 3:
在带有 TkAgg 后端的 Ubuntu 12.04 下,这会使窗口占据整个屏幕:
mng = plt.get_current_fig_manager()
mng.resize(*mng.window.maxsize())
解决方案 4:
这应该可行(至少对于TkAgg 来说):
wm = plt.get_current_fig_manager()
wm.window.state('zoomed')
(采用上面的方法并使用 Tkinter,有没有办法在不明显缩放窗口的情况下获得可用的屏幕尺寸?)
解决方案 5:
对我来说,上述方法都不起作用。我在 Ubuntu 14.04 上使用包含 matplotlib 1.3.1 的 Tk 后端。
以下代码创建一个全屏绘图窗口,它与最大化不同,但它很好地满足了我的目的:
from matplotlib import pyplot as plt
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
plt.show()
解决方案 6:
我通常使用
mng = plt.get_current_fig_manager()
mng.frame.Maximize(True)
在调用之前plt.show()
,我得到了一个最大化的窗口。这仅适用于“wx”后端。
编辑:
对于 Qt4Agg 后端,请参阅 kwerenda 的回答。
解决方案 7:
我迄今为止最大的努力,支持不同的后端:
from platform import system
def plt_maximize():
# See discussion: https://stackoverflow.com/questions/12439588/how-to-maximize-a-plt-show-window-using-python
backend = plt.get_backend()
cfm = plt.get_current_fig_manager()
if backend == "wxAgg":
cfm.frame.Maximize(True)
elif backend == "TkAgg":
if system() == "Windows":
cfm.window.state("zoomed") # This is windows only
else:
cfm.resize(*cfm.window.maxsize())
elif backend == "QT4Agg":
cfm.window.showMaximized()
elif callable(getattr(cfm, "full_screen_toggle", None)):
if not getattr(cfm, "flag_is_max", None):
cfm.full_screen_toggle()
cfm.flag_is_max = True
else:
raise RuntimeError("plt_maximize() is not implemented for current backend:", backend)
解决方案 8:
我mng.frame.Maximize(True) AttributeError: FigureManagerTkAgg instance has no attribute 'frame'
也明白。
然后我查看了属性mng
,发现了这个:
mng.window.showMaximized()
这对我有用。
所以有同样困扰的人可以尝试一下这个。
顺便说一下,我的Matplotlib版本是1.3.1。
解决方案 9:
我发现这个适用于 Ubuntu 的全屏模式
#Show full screen
mng = plt.get_current_fig_manager()
mng.full_screen_toggle()
解决方案 10:
这有点儿不方便,可能不便于携带,只有当你想快速而又粗略地使用它时才行。如果我将图形设置为比屏幕大得多,它就会占据整个屏幕。
fig = figure(figsize=(80, 60))
事实上,在装有 Qt4Agg 的 Ubuntu 16.04 中,如果窗口大于屏幕,它会最大化窗口(而不是全屏)。(如果您有两个显示器,它只会在其中一个上最大化)。
解决方案 11:
在 Win 10 上完美运行的一个解决方案。
import matplotlib.pyplot as plt
plt.plot(x_data, y_data)
mng = plt.get_current_fig_manager()
mng.window.state("zoomed")
plt.show()
解决方案 12:
import matplotlib.pyplot as plt
def maximize():
plot_backend = plt.get_backend()
mng = plt.get_current_fig_manager()
if plot_backend == 'TkAgg':
mng.resize(*mng.window.maxsize())
elif plot_backend == 'wxAgg':
mng.frame.Maximize(True)
elif plot_backend == 'Qt4Agg':
mng.window.showMaximized()
maximize()
然后调用之前的函数plt.show()
解决方案 13:
对于后端GTK3Agg,使用maximize()
– 特别是小写的m:
manager = plt.get_current_fig_manager()
manager.window.maximize()
在 Ubuntu 20.04 中使用 Python 3.8 进行了测试。
解决方案 14:
当聚焦于某个图时按下f
键(或ctrl+f
1.2rc1 中)将全屏显示图窗口。不是完全最大化,但可能更好。
除此之外,为了真正实现最大化,您将需要使用 GUI Toolkit 特定的命令(如果它们存在于您的特定后端)。
高血压
解决方案 15:
这是一个基于@Pythonio的答案的函数。我将其封装成一个函数,该函数自动检测它正在使用哪个后端并执行相应的操作。
def plt_set_fullscreen():
backend = str(plt.get_backend())
mgr = plt.get_current_fig_manager()
if backend == 'TkAgg':
if os.name == 'nt':
mgr.window.state('zoomed')
else:
mgr.resize(*mgr.window.maxsize())
elif backend == 'wxAgg':
mgr.frame.Maximize(True)
elif backend == 'Qt4Agg':
mgr.window.showMaximized()
解决方案 16:
在我的版本(Python 3.6、Eclipse、Windows 7)中,上面给出的代码片段不起作用,但通过 Eclipse/pydev 给出的提示(输入:mng. 后),我发现:
mng.full_screen_toggle()
看来使用 mng-commands 只适用于本地开发......
解决方案 17:
尝试使用 'Figure.set_size_inches' 方法,并附加额外的关键字参数forward=True
。根据文档,这应该可以调整图形窗口的大小。
这是否真的发生取决于您使用的操作系统。
解决方案 18:
好的,这就是对我有用的方法。我使用了整个 showMaximize() 选项,它确实会根据图形的大小调整窗口大小,但它不会扩展并“适合”画布。我通过以下方法解决了这个问题:
mng = plt.get_current_fig_manager()
mng.window.showMaximized()
plt.tight_layout()
plt.savefig('Images/SAVES_PIC_AS_PDF.pdf')
plt.show()
解决方案 19:
对于基于 Tk 的后端(TkAgg),这两个选项可以最大化和全屏显示窗口:
plt.get_current_fig_manager().window.state('zoomed')
plt.get_current_fig_manager().window.attributes('-fullscreen', True)
当绘图到多个窗口时,您需要为每个窗口写入以下内容:
data = rasterio.open(filepath)
blue, green, red, nir = data.read()
plt.figure(1)
plt.subplot(121); plt.imshow(blue);
plt.subplot(122); plt.imshow(red);
plt.get_current_fig_manager().window.state('zoomed')
rgb = np.dstack((red, green, blue))
nrg = np.dstack((nir, red, green))
plt.figure(2)
plt.subplot(121); plt.imshow(rgb);
plt.subplot(122); plt.imshow(nrg);
plt.get_current_fig_manager().window.state('zoomed')
plt.show()
在这里,两个“图形”都绘制在单独的窗口中。使用变量,例如
figure_manager = plt.get_current_fig_manager()
可能不会最大化第二个窗口,因为变量仍然引用第一个窗口。
解决方案 20:
在尝试实现相同目标时,我从查看的线程中收集了一些答案。这是我现在正在使用的函数,它可以最大化所有图,并且并不真正关心正在使用的后端。我在脚本末尾运行它。它仍然会遇到其他人使用多屏幕设置时提到的问题,因为 fm.window.maxsize() 将获取总屏幕尺寸,而不仅仅是当前显示器的尺寸。如果您知道所需的屏幕尺寸,则可以用元组 (width_inches, height_inches) 替换 *fm.window.maxsize()。
从功能上讲,这一切只是获取一个图形列表,然后将其大小调整为 matplotlibs 对当前最大窗口大小的当前解释。
def maximizeAllFigures():
'''
Maximizes all matplotlib plots.
'''
for i in plt.get_fignums():
plt.figure(i)
fm = plt.get_current_fig_manager()
fm.resize(*fm.window.maxsize())
解决方案 21:
我已经尝试了上述大多数解决方案,但它们都无法在我的装有 Python 3.10.5 的 Windows 10 上运行良好。
下面是我发现的在我这边运行良好的东西。
import ctypes
mng = plt.get_current_fig_manager()
mng.resize(ctypes.windll.user32.GetSystemMetrics(0), ctypes.windll.user32.GetSystemMetrics(1))
解决方案 22:
尝试plt.figure(figsize=(6*3.13,4*3.13))
让情节变得更大一些。
解决方案 23:
这并不一定会最大化您的窗口,但它会根据图形的大小调整窗口大小:
from matplotlib import pyplot as plt
F = gcf()
Size = F.get_size_inches()
F.set_size_inches(Size[0]*2, Size[1]*2, forward=True)#Set forward to True to resize window along with plot in figure.
plt.show() #or plt.imshow(z_array) if using an animation, where z_array is a matrix or numpy array
这也可能有帮助:http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html
解决方案 24:
以下内容可能适用于所有后端,但我仅在 QT 上进行了测试:
import numpy as np
import matplotlib.pyplot as plt
import time
plt.switch_backend('QT4Agg') #default on my system
print('Backend: {}'.format(plt.get_backend()))
fig = plt.figure()
ax = fig.add_axes([0,0, 1,1])
ax.axis([0,10, 0,10])
ax.plot(5, 5, 'ro')
mng = plt._pylab_helpers.Gcf.figs.get(fig.number, None)
mng.window.showMaximized() #maximize the figure
time.sleep(3)
mng.window.showMinimized() #minimize the figure
time.sleep(3)
mng.window.showNormal() #normal figure
time.sleep(3)
mng.window.hide() #hide the figure
time.sleep(3)
fig.show() #show the previously hidden figure
ax.plot(6,6, 'bo') #just to check that everything is ok
plt.show()
解决方案 25:
此代码应该对今天的 matplotlib 有帮助,
'zoomed' 在 Windows 上运行,但在其他系统上可能会有所不同或表现不同。
import matplotlib.pyplot as plt
import numpy as np
y = np.array([35, 25, 25, 15])
plt.pie(y)
manager = plt.get_current_fig_manager()
# this line will minimize the window after 0 ms of the window being displayed
# manager.window.after(0, lambda: manager.window.iconify())
# this line will restored the window to normal after 0 ms of the window being displayed
# manager.window.after(0, lambda: manager.window.state('normal'))
# this line will maximize the window after 0 ms of the window being displayed
manager.window.after(0, lambda: manager.window.state('zoomed'))
plt.show()
扫码咨询,免费领取项目管理大礼包!