Skip to content

Instantly share code, notes, and snippets.

@vigilantPotato
Created May 12, 2024 06:11
Show Gist options
  • Select an option

  • Save vigilantPotato/5f473ed69d851880425b7b9b3fbdfc05 to your computer and use it in GitHub Desktop.

Select an option

Save vigilantPotato/5f473ed69d851880425b7b9b3fbdfc05 to your computer and use it in GitHub Desktop.
matplotlib legend setting example
import ctypes
import tkinter
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from tkinter import ttk
legend_position_dict = {
0:"best",
1:"upper right",
2:"upper left",
3:"lower left",
4:"lower right",
5:"right",
6:"center left",
7:"center right",
8:"lower center",
9:"upper center",
10:"center",
}
class LegendSetting(tkinter.Toplevel):
def __init__(self, root, legend):
self.legend = legend
self.fig = legend.parent.get_figure()
super().__init__(root)
#legend on/off chechbutton
self.on_off_var = tkinter.BooleanVar(self, value=True)
on_off = tkinter.Checkbutton(
self,
text="show legend",
variable=self.on_off_var,
command=self.update_legend_setting
)
on_off.pack()
#position setting combobox
self.position_var = tkinter.StringVar(self)
position_select_box = ttk.Combobox(
self,
state="readonly",
values=list(legend_position_dict.values()),
textvariable=self.position_var,
)
position_select_box.set("best")
position_select_box.bind('<<ComboboxSelected>>', self.combobox_selected)
position_select_box.pack()
#draggable on/off chechbutton
self.draggable_var = tkinter.BooleanVar(self, value=False)
draggable = tkinter.Checkbutton(
self,
text="draggable",
variable=self.draggable_var,
command=self.update_legend_setting,
)
draggable.pack()
def update_legend_setting(self):
self.legend.set_visible(self.on_off_var.get())
self.legend.set_loc(self.position_var.get())
self.legend.set_draggable(self.draggable_var.get())
self.fig.canvas.draw()
def combobox_selected(self, event):
self.on_off_var.set(True)
self.draggable_var.set(False)
self.update_legend_setting()
if __name__ == "__main__":
ctypes.windll.shcore.SetProcessDpiAwareness(1)
root = tkinter.Tk()
#create graph objects
x = np.linspace(0, 10, 500)
fig, ax = plt.subplots()
ax.plot(x, np.sin(x), label="x")
ax.plot(x, np.sin(2*x), label="2x")
ax.plot(x, np.sin(3*x), label="3x")
#set title, legend
fig.suptitle("legend setting example")
legend = ax.legend()
legend_setting_window = LegendSetting(root, legend)
#set graph to tkinter window
canvas = FigureCanvasTkAgg(fig, root)
toolbar = NavigationToolbar2Tk(canvas, root)
canvas.get_tk_widget().pack() #show graph
plt.tight_layout()
plt.close()
root.mainloop()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment