divenex
divenex

Reputation: 17158

How to determine screen size in matplotlib

I am looking for a general way to get the screen size in pixels using matplotlib with any interactive backend (e.g. TkAgg, Qt4Agg, or macosx).

I am trying to write a function which can open a window at a set of standard locations on the screen like e.g. the right half of the screen, or the top-right corner.

I wrote a working solution here, copied below, but it requires one to use full_screen_toggle() (as suggested here) to create a full-screen window to measure its size.

I am looking for a way to get the screen size without creating a full-screen window and then changing its size.

import matplotlib.pyplot as plt

def move_figure(position="top-right"):
    '''
    Move and resize a window to a set of standard positions on the screen.
    Possible positions are:
    top, bottom, left, right, top-left, top-right, bottom-left, bottom-right
    '''

    mgr = plt.get_current_fig_manager()
    mgr.full_screen_toggle()  # primitive but works to get screen size
    py = mgr.canvas.height()
    px = mgr.canvas.width()

    d = 10  # width of the window border in pixels
    if position == "top":
        # x-top-left-corner, y-top-left-corner, x-width, y-width (in pixels)
        mgr.window.setGeometry(d, 4*d, px - 2*d, py/2 - 4*d)
    elif position == "bottom":
        mgr.window.setGeometry(d, py/2 + 5*d, px - 2*d, py/2 - 4*d)
    elif position == "left":
        mgr.window.setGeometry(d, 4*d, px/2 - 2*d, py - 4*d)
    elif position == "right":
        mgr.window.setGeometry(px/2 + d, 4*d, px/2 - 2*d, py - 4*d)
    elif position == "top-left":
        mgr.window.setGeometry(d, 4*d, px/2 - 2*d, py/2 - 4*d)
    elif position == "top-right":
        mgr.window.setGeometry(px/2 + d, 4*d, px/2 - 2*d, py/2 - 4*d)
    elif position == "bottom-left":
        mgr.window.setGeometry(d, py/2 + 5*d, px/2 - 2*d, py/2 - 4*d)
    elif position == "bottom-right":
        mgr.window.setGeometry(px/2 + d, py/2 + 5*d, px/2 - 2*d, py/2 - 4*d)


if __name__ == '__main__':

    # Usage example for move_figure()

    plt.figure(1)
    plt.plot([0, 1])
    move_figure("top-right")

    plt.figure(2)
    plt.plot([0, 3])
    move_figure("bottom-right")

Upvotes: 5

Views: 9945

Answers (2)

Adam V. Steele
Adam V. Steele

Reputation: 639

This works for TKagg

import matplotlib.pyplot as plt

window = plt.get_current_fig_manager().window
screen_x, screen_y = window.wm_maxsize()

#or
screen_y = window.winfo_screenheight()
screen_x = window.winfo_screenwidth()

Only odd thing I've seen is sometimes the y size is off by about 22 px.

Upvotes: 3

Vidhya G
Vidhya G

Reputation: 2320

This works for OS X:

import AppKit
[(screen.frame().size.width, screen.frame().size.height) for screen in AppKit.NSScreen.screens()]

The Apple document on the NSScreen class.

Upvotes: 1

Related Questions