Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate matplotlib NavigationToolbar2Tk to make it vertical

I have 3 plots like this in a Tkinter window

enter image description here

Is it possible to orient the NavigationToolbar2Tk vertically so I can place it on the left of the plot ?

I didn't find any documentation or thread about something similar.

Thanks

like image 690
Yohann Avatar asked May 28 '26 00:05

Yohann


1 Answers

You need to create a derived class from NavigationToolbar2Tk to override the default horizontal orientation.

Below is an example (based on the "Embedding in Tk" example):

import tkinter as tk

from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.figure import Figure
import numpy as np

class VerticalNavigationToolbar2Tk(NavigationToolbar2Tk):
   def __init__(self, canvas, window):
      super().__init__(canvas, window, pack_toolbar=False)

   # override _Button() to re-pack the toolbar button in vertical direction
   def _Button(self, text, image_file, toggle, command):
      b = super()._Button(text, image_file, toggle, command)
      b.pack(side=tk.TOP) # re-pack button in vertical direction
      return b

   # override _Spacer() to create vertical separator
   def _Spacer(self):
      s = tk.Frame(self, width=26, relief=tk.RIDGE, bg="DarkGray", padx=2)
      s.pack(side=tk.TOP, pady=5) # pack in vertical direction
      return s

   # disable showing mouse position in toolbar
   def set_message(self, s):
      pass

root = tk.Tk()
root.wm_title("Embedding in Tk")

fig = Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot().plot(t, 2 * np.sin(2 * np.pi * t))

canvas = FigureCanvasTkAgg(fig, master=root)
canvas.draw()
canvas.get_tk_widget().pack(side=tk.RIGHT, fill=tk.BOTH, expand=1)

toolbar = VerticalNavigationToolbar2Tk(canvas, root)
toolbar.update()
toolbar.pack(side=tk.LEFT, fill=tk.Y)

root.mainloop()

And the output:

enter image description here

like image 154
acw1668 Avatar answered May 30 '26 13:05

acw1668



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!