Reputation: 89
I have a problem with the zoom of the NavigationToolbar2Tk
from tkinter
. I set a fixed width=200
for my plot. When I zoom into the plot, this width remains (logical). The problem is, when I zoom in, the bars with a width=200
are too big and the plot becomes confusing when two bars are side by side or behind each other. How can I change the width=10 when zooming is activ?
My previous code is below:
# ___________________________________________________________________________
# Library
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
import tkinter as tk
import numpy as np
# ___________________________________________________________________________
# Maintenance Array
Maintenance_km = np.array([0,3,400,400,1700,1850,1600,4,1000,1000,2000,3000,3040,3040,80000,80090])
Maintenance_cost = np.array([4,500,500,1000,2000,2040,2040,10,40,500,2400,2700,2850,2600,3000,3150])
# ___________________________________________________________________________
# Main
Vis = tk.Tk()
Vis.title("Main") # titel
# ___________________________________________________________________________
# Plot
fig, ax = plt.subplots(1, 1, figsize=(20,5), facecolor = "white")
Plot_Maintenace_cost2 = plt.bar(Maintenance_km, Maintenance_cost,
bottom=-0,
color="#C5E0B4",
ec="black",
width=200,
label="Maintenance_cost")
ax.spines["bottom"].set_position("zero")
ax.spines["top"].set_color("none")
ax.spines["right"].set_color("none")
ax.spines["left"].set_color("none")
ax.tick_params(axis="x", length=20)
_, xmax = ax.get_xlim()
ymin, ymax = ax.get_ylim()
ax.set_xlim(-15, xmax)
ax.set_ylim(ymin, ymax+10) # legend
ax.text(xmax, -5, "km", ha="right", va="top", size=14)
plt.legend(ncol=5, loc="upper left")
plt.tight_layout()
# ___________________________________________________________________________
# Canvas, Toolbar
canvas = FigureCanvasTkAgg(fig, master=Vis)
canvas.draw() # TK-Drawingarea
canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=True)
canvas._tkcanvas.pack(side = tk.TOP, fill = tk.BOTH, expand = True)
toolbar = NavigationToolbar2Tk(canvas, Vis)
toolbar.update()
Vis.mainloop()
Upvotes: 1
Views: 266
Reputation: 4537
You could updated the plot when the limits of the x-axis change (like in this question)
def on_xlims_change(axes):
# Get the current limits of the x axis
x_lim = ax.get_xlim()
x_width = x_lim[1] - x_lim[0]
# Just an example, you can use your own logic here
new_width = x_width / 200 # Ensure a fixed ratio of xaxis to bar width
# new_width = 200 if x_width > 10000 else 10
# Update all bars
for b in Plot_Maintenace_cost2:
b.set_width(new_width)
ax.callbacks.connect('xlim_changed', on_xlims_change)
Upvotes: 1