简体   繁体   中英

Python/Matplotlib - Figure Borders in wxPython

I have a matplotlib figure on a canvas on a wxpython panel. My application is run real-time and the user can re-size the window frame. However, when this happens, the borders around my axes go out of whack.

I know I can use the function fig.subplots_adjust to adjust the borders, but the values specified in the function are percentages, so there is a TON of wasted space around the borders when maximized, even though the space is just right when the window is smaller.

Is there anything similar to this function where I can specify the border in something like pixels so that the border is the same width no matter what size the frame is?

As always, Thanks!

Here is an example of how this can be done. The code defines a function which translates pixel border values into percentages based on the current figure size. It also hooks up an event listener that will adjust the borders when the figure is resized:

import numpy
import matplotlib.pyplot as plt

def adjust_borders(fig, targets):
    "Translate desired pixel sizes into percentages based on figure size."
    dpi = fig.get_dpi()
    width, height = [float(v * dpi) for v in fig.get_size_inches()]
    conversions = {
        'top': lambda v: 1.0 - (v / height),
        'bottom': lambda v: v / height,
        'right': lambda v: 1.0 - (v / width),
        'left': lambda v: v / width,
        'hspace': lambda v: v / height,
        'wspace': lambda v: v / width,
        }
    opts = dict((k, conversions[k](v)) for k, v in targets.items())
    fig.subplots_adjust(**opts)

fig = plt.figure(figsize=(7, 5))
for i in range(4):
    ax = fig.add_subplot(2, 2, i+1)
    ax.plot([1,2,3], [4,5,1])
    ax.set_xticks([])
    ax.set_yticks([])

# target sizes in pixels.
targets = dict(left=10, right=10, top=10, bottom=30, hspace=30, wspace=30)
# hook up a function to adjust the borders when the window is resized
fig.canvas.mpl_connect('resize_event', lambda e: adjust_borders(fig, targets))
adjust_borders(fig, targets)
plt.show()

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