I have a gui with an empty tk.Canvas
widget which I want to fill during runtime with a matplotlib
plot.
However, when adding the plot, it forces the gui to use the plot size instead of using the provided space, moving stuff around in the gui.
What can I do such that the plot is created with the same dimensions as the Canvas?
MWE:
import matplotlib as mpl
mpl.use('TkAgg')
import tkinter as tk
from matplotlib import figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
root = tk.Tk()
def show_plot():
fig = figure.Figure()
ax=fig.add_subplot()
ax.scatter([1, 2, 3, 4], [4, 7, 2, 4])
canv = FigureCanvasTkAgg(fig, canvas)
canv.draw()
canv.get_tk_widget().pack(fill=tk.BOTH, expand=1)
canvas = tk.Canvas(root, width=600, height=600)
canvas.pack(fill=tk.NONE, expand=0)
tk.Button(root, text='show plot', command=show_plot).pack()
root.mainloop()
I already tried changing the fill
and expand
parameters in the .pack()
calls for both the plot and the canvas but that didn't work.
I have a gui with an empty tk.Canvas
widget which I want to fill during runtime with a matplotlib
plot.
However, when adding the plot, it forces the gui to use the plot size instead of using the provided space, moving stuff around in the gui.
What can I do such that the plot is created with the same dimensions as the Canvas?
MWE:
import matplotlib as mpl
mpl.use('TkAgg')
import tkinter as tk
from matplotlib import figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
root = tk.Tk()
def show_plot():
fig = figure.Figure()
ax=fig.add_subplot()
ax.scatter([1, 2, 3, 4], [4, 7, 2, 4])
canv = FigureCanvasTkAgg(fig, canvas)
canv.draw()
canv.get_tk_widget().pack(fill=tk.BOTH, expand=1)
canvas = tk.Canvas(root, width=600, height=600)
canvas.pack(fill=tk.NONE, expand=0)
tk.Button(root, text='show plot', command=show_plot).pack()
root.mainloop()
I already tried changing the fill
and expand
parameters in the .pack()
calls for both the plot and the canvas but that didn't work.
1 Answer
Reset to default 0It turned out to be quite simple: I just have to specify the size of the matplotlib figure:
fig = figure.Figure(fig_size=(6, 8), dpi=100)
will generate a plot that is 600 by 800 pixels. Replacing 6 and 8 by the width and height (each divided by the dpi) of the parent canvas solves the problem.
For more information on how to work with exact pixels in matplotlib see Specifying and saving a figure with exact size in pixels
.pack_propagate(0)
, or use.place()
instead of.pack()
, to keep it from resizing to fit the actual Canvas. Or, if the purpose of using a Canvas was to make the plot scrollable, add the plot with.create_window()
rather than.place()
. – jasonharper Commented Mar 17 at 13:38