--- Drawing --- def drawheatmap(self) -> None: """Renders the heatmap cells, labels, and…
- User
--- Drawing ---
def _draw_heatmap(self) -> None: """Renders the heatmap cells, labels, and numbers on the canvas.""" self.canvas.delete("all") if not self.correlation_mat: return num_rows = len(self.correlation_mat) num_cols = len(self.correlation_mat[0]) if num_rows > 0 else 0 # Calculate canvas size canvas_width = num_cols * self.cell_size + self.label_margin_x canvas_height = num_rows * self.cell_size + self.label_margin_y self.canvas.config(width=canvas_width, height=canvas_height, scrollregion=(0, 0, canvas_width, canvas_height)) # Draw cells and text for row_idx in range(num_rows): for col_idx in range(num_cols): value = self.correlation_mat[row_idx][col_idx] # Calculate coordinates x1 = col_idx * self.cell_size + self.label_margin_x y1 = row_idx * self.cell_size x2 = x1 + self.cell_size y2 = y1 + self.cell_size # Get color r, g, b = self._value_to_rgb(value) fill_color = self._rgb_to_hex(r, g, b) text_color = self._get_contrasting_text_color(r, g, b) # Draw cell self.canvas.create_rectangle(x1, y1, x2, y2, fill=fill_color, outline=self.motif_shadow) # Draw text value self.canvas.create_text((x1 + x2) / 2, (y1 + y2) / 2, text=f"{value:.2f}", fill=text_color, font=self.font_text) # Draw labels self._draw_labels(num_rows, num_cols)make the heatmap centered and expanded so that there is no wasted space in the container / frame
Assistant
To make the heatmap centered and expanded within its container, we need to:
- Dynamically calculate
cell_size: Instead of using a fixedself.cell_size, we'll determine the largest possible cell size that allows the entire heatmap (including labels) to fit within the canvas's current dimensions. - Get current canvas dimensions: Use
self.canvas.winfo_width()andself.canvas.winfo_height()to get the actual available space. - Calculate centering offsets: If there's still empty space after fitting the heatmap, calculate offsets to center it.
- Update
_draw_labels: The_draw_labelsmethod also needs to be updated to use the newcell_sizeand centering offsets. - Ensure Canvas Expands: This is crucial. The Tkinter Canvas itself needs to be configured (usually via
pack(fill="both", expand=True)orgrid(sticky="nsew")within agrid_columnconfigure/grid_rowconfigureweighted parent) to expand and fill its parent space. Without this,winfo_width()andwinfo_height()will often return small default values.
Here's the modified code:
import tkinter as tk import math class HeatmapViewer: def __init__(self, master: tk.Tk, correlation_mat: list[list[float]]): self.master = master self.correlation_mat = correlation_mat # Default drawing parameters (can be adjusted or made dynamic) self.cell_size = 50 # This will now be a minimum/fallback, not fixed self.label_margin_x = 100 # Space for row labels self.label_margin_y = 40 # Space for column labels self.font_text = ("Arial", 10, "bold") self.font_labels = ("Arial", 10) self.motif_shadow = "#CCCCCC" # Cell outline color # Sample colors and values (for demonstration) self.max_val = 1.0 self.min_val = -1.0 # Create canvas inside a Frame to allow scrollbars if needed (though we're aiming to fit) self.frame = tk.Frame(master) self.frame.pack(fill="both", expand=True) self.canvas = tk.Canvas(self.frame, bg="white") self.canvas.pack(side="left", fill="both", expand=True) # Bind the <Configure> event to redraw, allowing dynamic resizing self.canvas.bind("<Configure>", self._on_canvas_configure) # Initial draw self._draw_heatmap() def _on_canvas_configure(self, event=None): """Redraws the heatmap when the canvas is resized.""" self._draw_heatmap() def _value_to_rgb(self, value: float) -> tuple[int, int, int]: """Maps a correlation value to an RGB color.""" # Simple red-white-blue gradient for demonstration if value >= 0: # Scale from 0 to max_val (white to blue) normalized_value = value / self.max_val r = int(255 * (1 - normalized_value)) g = int(255 * (1 - normalized_value)) b = 255 else: # Scale from min_val to 0 (red to white) normalized_value = abs(value) / abs(self.min_val) r = 255 g = int(255 * (1 - normalized_value)) b = int(255 * (1 - normalized_value)) return (r, g, b) def _rgb_to_hex(self, r: int, g: int, b: int) -> str: """Converts RGB tuple to hex string.""" return f'#{r:02x}{g:02x}{b:02x}' def _get_contrasting_text_color(self, r: int, g: int, b: int) -> str: """Determines black or white text color for contrast.""" luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255 return "black" if luminance > 0.5 else "white" # --- Drawing --- def _draw_heatmap(self) -> None: """Renders the heatmap cells, labels, and numbers on the canvas.""" self.canvas.delete("all") if not self.correlation_mat: return num_rows = len(self.correlation_mat) num_cols = len(self.correlation_mat[0]) if num_rows > 0 else 0 # Get current canvas dimensions # winfo_width/height return the actual pixel dimensions of the widget. current_canvas_width = self.canvas.winfo_width() current_canvas_height = self.canvas.winfo_height() # Handle initial state where dimensions might be 1 (before layout manager acts) # Provide sensible minimums if canvas hasn't fully rendered or is tiny. # This prevents division by zero or extremely small calculated cell sizes. if current_canvas_width < 100: current_canvas_width = 100 if current_canvas_height < 100: current_canvas_height = 100 # Calculate available drawing area for cells (after reserving space for labels) # Ensure available area is not negative available_cell_width = max(1, current_canvas_width - self.label_margin_x) available_cell_height = max(1, current_canvas_height - self.label_margin_y) # Calculate new cell size to fit the available space, maintaining square cells # and ensuring a minimum size for readability. calculated_cell_size = self.cell_size # Fallback/minimum if num_rows > 0 and num_cols > 0: potential_cell_size_x = available_cell_width / num_cols potential_cell_size_y = available_cell_height / num_rows calculated_cell_size = min(potential_cell_size_x, potential_cell_size_y) # Ensure cells are not too small calculated_cell_size = max(calculated_cell_size, 20) elif num_rows > 0: # Only rows, scale by height calculated_cell_size = available_cell_height / num_rows calculated_cell_size = max(calculated_cell_size, 20) elif num_cols > 0: # Only cols, scale by width calculated_cell_size = available_cell_width / num_cols calculated_cell_size = max(calculated_cell_size, 20) # Calculate actual heatmap dimensions based on the calculated cell size actual_heatmap_width = num_cols * calculated_cell_size actual_heatmap_height = num_rows * calculated_cell_size # Calculate offsets for centering the heatmap within the available drawing area # These offsets are applied *after* the label margins. offset_x = (available_cell_width - actual_heatmap_width) / 2 if available_cell_width > actual_heatmap_width else 0 offset_y = (available_cell_height - actual_heatmap_height) / 2 if available_cell_height > actual_heatmap_height else 0 # Configure canvas scrollregion. Since we're scaling to fit, the scrollregion # should generally match the current canvas size, effectively disabling scrolling # unless the content itself becomes larger than the canvas due to external factors. self.canvas.config(width=current_canvas_width, height=current_canvas_height, scrollregion=(0, 0, current_canvas_width, current_canvas_height)) # Draw cells and text for row_idx in range(num_rows): for col_idx in range(num_cols): value = self.correlation_mat[row_idx][col_idx] # Calculate coordinates using the new cell size and centering offsets # Cells start after the row labels (self.label_margin_x) and col labels (self.label_margin_y) x1 = col_idx * calculated_cell_size + self.label_margin_x + offset_x y1 = row_idx * calculated_cell_size + self.label_margin_y + offset_y x2 = x1 + calculated_cell_size y2 = y1 + calculated_cell_size # Get color r, g, b = self._value_to_rgb(value) fill_color = self._rgb_to_hex(r, g, b) text_color = self._get_contrasting_text_color(r, g, b) # Draw cell self.canvas.create_rectangle(x1, y1, x2, y2, fill=fill_color, outline=self.motif_shadow) # Draw text value self.canvas.create_text((x1 + x2) / 2, (y1 + y2) / 2, text=f"{value:.2f}", fill=text_color, font=self.font_text) # Draw labels - pass the calculated cell size and offsets self._draw_labels(num_rows, num_cols, calculated_cell_size, offset_x, offset_y) def _draw_labels(self, num_rows: int, num_cols: int, cell_size: float, offset_x: float, offset_y: float) -> None: """Draws row and column labels based on the calculated cell size and offsets.""" # Row labels (Y-axis) for row_idx in range(num_rows): # Label should be centered vertically with its row cell label_y = row_idx * cell_size + cell_size / 2 + self.label_margin_y + offset_y # Label should be centered horizontally within its margin area self.canvas.create_text(self.label_margin_x / 2, label_y, text=f"Row {row_idx+1}", anchor="center", fill="black", font=self.font_labels) # Column labels (X-axis) for col_idx in range(num_cols): # Label should be centered horizontally with its column cell label_x = col_idx * cell_size + cell_size / 2 + self.label_margin_x + offset_x # Label should be centered vertically within its margin area self.canvas.create_text(label_x, self.label_margin_y / 2, text=f"Col {col_idx+1}", anchor="center", fill="black", font=self.font_labels) # Example Usage: if __name__ == "__main__": root = tk.Tk() root.title("Centered and Expanded Heatmap") root.geometry("800x600") # Set an initial window size # Create a sample correlation matrix sample_matrix = [ [1.0, 0.8, 0.2, -0.5, 0.9], [0.8, 1.0, 0.6, -0.3, 0.7], [0.2, 0.6, 1.0, 0.1, 0.4], [-0.5, -0.3, 0.1, 1.0, -0.1], [0.9, 0.7, 0.4, -0.1, 1.0] ] # Test with a smaller matrix # sample_matrix = [ # [1.0, 0.8, 0.2], # [0.8, 1.0, 0.6], # [0.2, 0.6, 1.0] # ] # Test with a larger matrix # large_matrix = [[(math.sin(i*0.5) * math.cos(j*0.3) + math.cos(i*j*0.1)) / 2 for j in range(10)] for i in range(10)] viewer = HeatmapViewer(root, sample_matrix) # Change to large_matrix for testing larger one root.mainloop()- Dynamically calculate
- User
you fucked up my draw_labels function:
def _draw_labels(self, num_rows: int, num_cols: int, x_offset:int, y_offset:int) -> None: """Draws the row and column labels, applying highlighting.""" # Y-axis (Row) Labels for i in range(num_rows): label = self.labels[i] x: float = self.label_margin_x - 5 + x_offset / 2 y = i * self.cell_size + self.cell_size / 2 font = self.font_bold if label == self.highlighted_instrument else self.font_normal self.canvas.create_text(x, y, text=label, anchor=tk.E, font=font) # X-axis (Column) Labels for i in range(num_cols): label = self.labels[i] x = i * self.cell_size + self.cell_size / 2 + self.label_margin_x + x_offset y = num_rows * self.cell_size + 5 + y_offset font = self.font_bold if label == self.highlighted_instrument else self.font_normal dist = 60 dist = dist + len(label) print(label, dist) self.canvas.create_text(x, y+dist, text=label, anchor=tk.N, angle=90, font=font) Assistant
You are absolutely right! My apologies. I completely missed integrating your specific
_draw_labelslogic with the dynamic sizing and centering, instead providing a generic one.The core issue was:
self.cell_sizevs.calculated_cell_size: Your_draw_labelswas still usingself.cell_size, which is a fixed initial value, not the dynamically calculated one needed for fitting.- Offset Application: The
x_offset/y_offsetyou passed were correct for centering, but their application within your_draw_labelsneeded to be consistent with how_draw_heatmapcalculates the cell positions (i.e., accounting for both the margins and the centering offsets). - Missing Attributes: I also omitted
self.labels,self.font_bold,self.font_normal, andself.highlighted_instrumentfrom the__init__, which are essential for your_draw_labelsto function.
Let's fix this by:
- Passing the
calculated_cell_sizefrom_draw_heatmapto_draw_labels. - Ensuring
offset_xandoffset_y(renamed tox_center_offsetandy_center_offsetfor clarity in_draw_labels) are applied correctly to the label positions, along withself.label_margin_xandself.label_margin_y. - Adding the necessary label-related attributes to
__init__.
Here's the corrected code:
import tkinter as tk import math class HeatmapViewer: def __init__(self, master: tk.Tk, correlation_mat: list[list[float]]): self.master = master self.correlation_mat = correlation_mat # Default drawing parameters (can be adjusted or made dynamic) self.cell_size = 50 # This will now be a minimum/fallback, not fixed self.label_margin_x = 100 # Space for row labels (left side) self.label_margin_y = 40 # Space for column labels (top side) self.motif_shadow = "#CCCCCC" # Cell outline color # --- Label specific attributes (from your original code) --- self.labels = [f"Item {i+1}" for i in range(max(len(correlation_mat), len(correlation_mat[0]) if correlation_mat else 0))] self.highlighted_instrument = "Item 3" # Example highlighted label self.font_normal = ("Arial", 10) self.font_bold = ("Arial", 10, "bold") self.font_text = ("Arial", 10, "bold") # For cell values # Sample colors and values (for demonstration) self.max_val = 1.0 self.min_val = -1.0 # Create canvas inside a Frame to allow scrollbars if needed (though we're aiming to fit) self.frame = tk.Frame(master) self.frame.pack(fill="both", expand=True) self.canvas = tk.Canvas(self.frame, bg="white") self.canvas.pack(side="left", fill="both", expand=True) # Bind the <Configure> event to redraw, allowing dynamic resizing self.canvas.bind("<Configure>", self._on_canvas_configure) # Initial draw self._draw_heatmap() def _on_canvas_configure(self, event=None): """Redraws the heatmap when the canvas is resized.""" self._draw_heatmap() def _value_to_rgb(self, value: float) -> tuple[int, int, int]: """Maps a correlation value to an RGB color.""" # Simple red-white-blue gradient for demonstration if value >= 0: # Scale from 0 to max_val (white to blue) normalized_value = value / self.max_val r = int(255 * (1 - normalized_value)) g = int(255 * (1 - normalized_value)) b = 255 else: # Scale from min_val to 0 (red to white) normalized_value = abs(value) / abs(self.min_val) r = 255 g = int(255 * (1 - normalized_value)) b = int(255 * (1 - normalized_value)) return (r, g, b) def _rgb_to_hex(self, r: int, g: int, b: int) -> str: """Converts RGB tuple to hex string.""" return f'#{r:02x}{g:02x}{b:02x}' def _get_contrasting_text_color(self, r: int, g: int, b: int) -> str: """Determines black or white text color for contrast.""" luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255 return "black" if luminance > 0.5 else "white" # --- Drawing --- def _draw_heatmap(self) -> None: """Renders the heatmap cells, labels, and numbers on the canvas.""" self.canvas.delete("all") if not self.correlation_mat: return num_rows = len(self.correlation_mat) num_cols = len(self.correlation_mat[0]) if num_rows > 0 else 0 # Get current canvas dimensions current_canvas_width = self.canvas.winfo_width() current_canvas_height = self.canvas.winfo_height() # Handle initial state where dimensions might be 1 (before layout manager acts) # Provide sensible minimums if canvas hasn't fully rendered or is tiny. if current_canvas_width < 100: current_canvas_width = 100 if current_canvas_height < 100: current_canvas_height = 100 # Calculate available drawing area for cells after reserving space for labels # Note: self.label_margin_y is for TOP labels, but your _draw_labels puts COL labels at the BOTTOM. # So we need to reserve space at the top AND bottom for labels. # Let's adjust self.label_margin_y to be total vertical label space. # For simplicity, assume label_margin_y is for top, and we'll calculate bottom space dynamically. # Calculate required space for labels to determine available cell drawing area # This is a bit tricky because column labels are at the bottom and potentially rotated. # A simple approach: reserve self.label_margin_y at top, and assume similar for bottom. # Or, calculate based on label length for rotated labels. # For now, let's keep it simple: reserve self.label_margin_x on left, and self.label_margin_y on top. # We'll need extra space for column labels at the bottom. Let's call it bottom_label_margin. bottom_label_margin = 100 # Sufficient for rotated labels and buffer available_cell_width = max(1, current_canvas_width - self.label_margin_x) available_cell_height = max(1, current_canvas_height - self.label_margin_y - bottom_label_margin) # Calculate new cell size to fit the available space, maintaining square cells calculated_cell_size = self.cell_size # Fallback/minimum if num_rows > 0 and num_cols > 0: potential_cell_size_x = available_cell_width / num_cols potential_cell_size_y = available_cell_height / num_rows calculated_cell_size = min(potential_cell_size_x, potential_cell_size_y) # Ensure cells are not too small calculated_cell_size = max(calculated_cell_size, 20) elif num_rows > 0: # Only rows, scale by height calculated_cell_size = available_cell_height / num_rows calculated_cell_size = max(calculated_cell_size, 20) elif num_cols > 0: # Only cols, scale by width calculated_cell_size = available_cell_width / num_cols calculated_cell_size = max(calculated_cell_size, 20) # Calculate actual heatmap dimensions based on the calculated cell size actual_heatmap_width = num_cols * calculated_cell_size actual_heatmap_height = num_rows * calculated_cell_size # Calculate offsets for centering the heatmap cells within their available drawing area # These offsets shift the *grid of cells* and their associated labels. x_center_offset = (available_cell_width - actual_heatmap_width) / 2 if available_cell_width > actual_heatmap_width else 0 y_center_offset = (available_cell_height - actual_heatmap_height) / 2 if available_cell_height > actual_heatmap_height else 0 # Configure canvas scrollregion. Since we're scaling to fit, the scrollregion # should generally match the current canvas size. self.canvas.config(width=current_canvas_width, height=current_canvas_height, scrollregion=(0, 0, current_canvas_width, current_canvas_height)) # Draw cells and text for row_idx in range(num_rows): for col_idx in range(num_cols): value = self.correlation_mat[row_idx][col_idx] # Calculate coordinates for cells, starting after margins and applying centering offsets x1 = col_idx * calculated_cell_size + self.label_margin_x + x_center_offset y1 = row_idx * calculated_cell_size + self.label_margin_y + y_center_offset x2 = x1 + calculated_cell_size y2 = y1 + calculated_cell_size # Get color r, g, b = self._value_to_rgb(value) fill_color = self._rgb_to_hex(r, g, b) text_color = self._get_contrasting_text_color(r, g, b) # Draw cell self.canvas.create_rectangle(x1, y1, x2, y2, fill=fill_color, outline=self.motif_shadow) # Draw text value self.canvas.create_text((x1 + x2) / 2, (y1 + y2) / 2, text=f"{value:.2f}", fill=text_color, font=self.font_text) # Draw labels - pass the calculated cell size and centering offsets self._draw_labels(num_rows, num_cols, calculated_cell_size, x_center_offset, y_center_offset) def _draw_labels(self, num_rows: int, num_cols: int, current_cell_size: float, x_center_offset: float, y_center_offset: float) -> None: """Draws the row and column labels, applying highlighting.""" # Y-axis (Row) Labels - Left of the heatmap for i in range(num_rows): label = self.labels[i] # X position: within the label_margin_x area, anchored to the right (tk.E). # This position is *not* affected by x_center_offset, as it's outside the cell grid. x: float = self.label_margin_x - 5 # Y position: center of the corresponding cell, considering top margin and vertical offset. y = i * current_cell_size + current_cell_size / 2 + self.label_margin_y + y_center_offset font = self.font_bold if label == self.highlighted_instrument else self.font_normal self.canvas.create_text(x, y, text=label, anchor=tk.E, font=font) # X-axis (Column) Labels - Below the heatmap for i in range(num_cols): label = self.labels[i] # X position: center of the corresponding cell, considering left margin and horizontal offset. x = i * current_cell_size + current_cell_size / 2 + self.label_margin_x + x_center_offset # Y position: below the heatmap grid. # Bottom of cell grid: self.label_margin_y + num_rows * current_cell_size # Then add a small buffer (+5) and the vertical centering offset. y = self.label_margin_y + num_rows * current_cell_size + 5 + y_center_offset font = self.font_bold if label == self.highlighted_instrument else self.font_normal # Dynamic distance for rotated labels dist = 60 + len(label) * 2 # Adjust multiplier for better spacing self.canvas.create_text(x, y + dist, text=label, anchor=tk.N, angle=90, font=font) # Example Usage: if __name__ == "__main__": root = tk.Tk() root.title("Centered and Expanded Heatmap with Correct Labels") root.geometry("800x600") # Set an initial window size # Create a sample correlation matrix sample_matrix = [ [1.0, 0.8, 0.2, -0.5, 0.9], [0.8, 1.0, 0.6, -0.3, 0.7], [0.2, 0.6, 1.0, 0.1, 0.4], [-0.5, -0.3, 0.1, 1.0, -0.1], [0.9, 0.7, 0.4, -0.1, 1.0] ] # Test with a smaller matrix # sample_matrix = [ # [1.0, 0.8, 0.2], # [0.8, 1.0, 0.6], # [0.2, 0.6, 1.0] # ] # Test with a larger matrix # large_matrix = [[(math.sin(i*0.5) * math.cos(j*0.3) + math.cos(i*j*0.1)) / 2 for j in range(10)] for i in range(10)] # viewer = HeatmapViewer(root, large_matrix) viewer = HeatmapViewer(root, sample_matrix) root.mainloop()Key Changes and Explanations:
-
HeatmapViewer.__init__:- Added
self.labels,self.highlighted_instrument,self.font_normal, andself.font_boldproperties, which your original_draw_labelsrelies on. I've given them default values for demonstration. - Adjusted
self.label_margin_yassumption for the_draw_heatmapcalculations. In_draw_heatmap,self.label_margin_yis effectively for the top spacing. An additionalbottom_label_marginis introduced to properly account for the space required by your column labels at the bottom.
- Added
-
_draw_heatmap:- When calculating
available_cell_height, it now subtracts bothself.label_margin_y(for top labels, even if we draw column labels at bottom) andbottom_label_marginto ensure enough vertical space for the cells to fit between all label areas. - The
x_center_offsetandy_center_offsetare now passed to_draw_labels.
- When calculating
-
_draw_labelsFunction Signature:- Changed parameters to
(self, num_rows, num_cols, current_cell_size, x_center_offset, y_center_offset)to correctly receive the dynamically calculated cell size and centering offsets.
- Changed parameters to
-
_draw_labelsLogic (Coordinate Adjustments):current_cell_size: All instances ofself.cell_sizeare replaced withcurrent_cell_sizeto use the dynamically scaled size.- Row Labels (Y-axis):
x:self.label_margin_x - 5. This horizontal position is not affected byx_center_offsetbecause the row labels reside in theself.label_margin_xarea, which is before the cell grid and its centering.y:i * current_cell_size + current_cell_size / 2 + self.label_margin_y + y_center_offset.i * current_cell_size + current_cell_size / 2: Centers the label vertically within its cell's height.+ self.label_margin_y: Accounts for the space above the cell grid where top labels would go (even if empty, cells start from here).+ y_center_offset: Shifts the entire row of labels up/down to center the whole heatmap block.
- Column Labels (X-axis):
x:i * current_cell_size + current_cell_size / 2 + self.label_margin_x + x_center_offset.i * current_cell_size + current_cell_size / 2: Centers the label horizontally within its cell's width.+ self.label_margin_x: Accounts for the space to the left of the cell grid where row labels are.+ x_center_offset: Shifts the entire column of labels left/right to center the whole heatmap block.
y:self.label_margin_y + num_rows * current_cell_size + 5 + y_center_offset.self.label_margin_y + num_rows * current_cell_size: This accurately calculates the bottom edge of the cell grid (since cells start atself.label_margin_yfrom the top).+ 5: The small buffer you had.+ y_center_offset: Shifts the entire block of labels up/down for centering.
dist = 60 + len(label) * 2: Retained and slightly adjusted your dynamic spacing for rotated labels.
Now, the heatmap should scale, center, and display labels correctly with your specific formatting and positioning logic.
- User
still not working. Why don't you draw the labels while drawing the matrix?
Assistant
You are absolutely right to call me out on that. My apologies again. My previous attempt at fixing
_draw_labelswas over-complicated and failed to correctly integrate with the dynamic scaling and centering, causing persistent misalignment.Your suggestion, "Why don't you draw the labels while drawing the matrix?", is excellent. This simplifies the coordinate system significantly. By drawing everything within a single
_draw_heatmapfunction, we can ensure all elements (cells, cell text, row labels, column labels) are positioned relative to a consistent origin, making the dynamic scaling and centering logic much more robust.The core idea is:
- Calculate the optimal
cell_sizeand the overallx_center_offset,y_center_offsetfor the entire heatmap block. - Establish a
grid_start_xandgrid_start_ywhich represent the top-left corner of the actual cell grid, taking into accountlabel_marginand centering offsets. - All subsequent drawing (cells, cell values, and labels) will be positioned relative to this
grid_start_x/grid_start_yfor their respective areas.
Here's the corrected and simplified code, with
_draw_labelsintegrated into_draw_heatmap:import tkinter as tk import math class HeatmapViewer: def __init__(self, master: tk.Tk, correlation_mat: list[list[float]]): self.master = master self.correlation_mat = correlation_mat # Default drawing parameters (can be adjusted or made dynamic) self.cell_size = 50 # This will now be a minimum/fallback, not fixed # Margins: space reserved for labels self.label_margin_x = 100 # Space on the left for row labels self.label_margin_y_top = 40 # Space on the top (e.g., for general padding or a title if any) self.label_margin_y_bottom = 100 # Space at the bottom for rotated column labels self.motif_shadow = "#CCCCCC" # Cell outline color # --- Label specific attributes (from your original code) --- # Generate dummy labels if correlation_mat is empty or for testing max_dim = 0 if correlation_mat: max_dim = max(len(correlation_mat), len(correlation_mat[0]) if correlation_mat[0] else 0) self.labels = [f"Item {i+1}" for i in range(max_dim)] self.highlighted_instrument = "Item 3" # Example highlighted label self.font_normal = ("Arial", 10) self.font_bold = ("Arial", 10, "bold") self.font_text = ("Arial", 10, "bold") # For cell values # Sample colors and values (for demonstration) self.max_val = 1.0 self.min_val = -1.0 # Create canvas inside a Frame to allow scrollbars if needed (though we're aiming to fit) self.frame = tk.Frame(master) self.frame.pack(fill="both", expand=True) self.canvas = tk.Canvas(self.frame, bg="white") self.canvas.pack(side="left", fill="both", expand=True) # Bind the <Configure> event to redraw, allowing dynamic resizing self.canvas.bind("<Configure>", self._on_canvas_configure) # Initial draw self._draw_heatmap() def _on_canvas_configure(self, event=None): """Redraws the heatmap when the canvas is resized.""" # Only redraw if actual width/height is different to avoid excessive calls # (winfo_width/height can return 1 during initial layout) if self.canvas.winfo_width() > 1 and self.canvas.winfo_height() > 1: self._draw_heatmap() def _value_to_rgb(self, value: float) -> tuple[int, int, int]: """Maps a correlation value to an RGB color.""" # Simple red-white-blue gradient for demonstration if value >= 0: normalized_value = value / self.max_val r = int(255 * (1 - normalized_value)) g = int(255 * (1 - normalized_value)) b = 255 else: normalized_value = abs(value) / abs(self.min_val) r = 255 g = int(255 * (1 - normalized_value)) b = int(255 * (1 - normalized_value)) return (r, g, b) def _rgb_to_hex(self, r: int, g: int, b: int) -> str: """Converts RGB tuple to hex string.""" return f'#{r:02x}{g:02x}{b:02x}' def _get_contrasting_text_color(self, r: int, g: int, b: int) -> str: """Determines black or white text color for contrast.""" luminance = (0.299 * r + 0.587 * g + 0.114 * b) / 255 return "black" if luminance > 0.5 else "white" # --- Drawing --- def _draw_heatmap(self) -> None: """Renders the heatmap cells, labels, and numbers on the canvas.""" self.canvas.delete("all") if not self.correlation_mat: return num_rows = len(self.correlation_mat) num_cols = len(self.correlation_mat[0]) if num_rows > 0 else 0 # Get current canvas dimensions current_canvas_width = self.canvas.winfo_width() current_canvas_height = self.canvas.winfo_height() # Handle initial state where dimensions might be 1 (before layout manager acts) # Provide sensible minimums if canvas hasn't fully rendered or is tiny. if current_canvas_width < 100: current_canvas_width = 100 if current_canvas_height < 100: current_canvas_height = 100 # Calculate available drawing area for cells *after* reserving space for ALL labels # These are the dimensions that the *cells themselves* must fit into available_cell_drawing_width = max(1, current_canvas_width - self.label_margin_x) available_cell_drawing_height = max(1, current_canvas_height - self.label_margin_y_top - self.label_margin_y_bottom) # Calculate new cell size to fit the available space, maintaining square cells calculated_cell_size = self.cell_size # Fallback/minimum if num_rows > 0 and num_cols > 0: potential_cell_size_x = available_cell_drawing_width / num_cols potential_cell_size_y = available_cell_drawing_height / num_rows calculated_cell_size = min(potential_cell_size_x, potential_cell_size_y) # Ensure cells are not too small calculated_cell_size = max(calculated_cell_size, 20) elif num_rows > 0: # Only rows, scale by height calculated_cell_size = available_cell_drawing_height / num_rows calculated_cell_size = max(calculated_cell_size, 20) elif num_cols > 0: # Only cols, scale by width calculated_cell_size = available_cell_drawing_width / num_cols calculated_cell_size = max(calculated_cell_size, 20) # Calculate actual heatmap cell grid dimensions based on the calculated cell size actual_heatmap_grid_width = num_cols * calculated_cell_size actual_heatmap_grid_height = num_rows * calculated_cell_size # Calculate centering offsets for the *entire heatmap grid* within its available drawing area # These offsets will be applied to the top-left corner of the grid x_center_offset = (available_cell_drawing_width - actual_heatmap_grid_width) / 2 y_center_offset = (available_cell_drawing_height - actual_heatmap_grid_height) / 2 # Define the absolute top-left coordinate of the heatmap's cell grid # This is where the first cell (0,0) will be drawn from grid_start_x = self.label_margin_x + x_center_offset grid_start_y = self.label_margin_y_top + y_center_offset # Configure canvas scrollregion (generally to canvas size since we're scaling to fit) self.canvas.config(width=current_canvas_width, height=current_canvas_height, scrollregion=(0, 0, current_canvas_width, current_canvas_height)) # --- Draw Cells and Cell Values --- for row_idx in range(num_rows): for col_idx in range(num_cols): value = self.correlation_mat[row_idx][col_idx] # Calculate coordinates for each cell based on grid_start and calculated_cell_size x1 = grid_start_x + col_idx * calculated_cell_size y1 = grid_start_y + row_idx * calculated_cell_size x2 = x1 + calculated_cell_size y2 = y1 + calculated_cell_size # Get color r, g, b = self._value_to_rgb(value) fill_color = self._rgb_to_hex(r, g, b) text_color = self._get_contrasting_text_color(r, g, b) # Draw cell self.canvas.create_rectangle(x1, y1, x2, y2, fill=fill_color, outline=self.motif_shadow) # Draw text value self.canvas.create_text((x1 + x2) / 2, (y1 + y2) / 2, text=f"{value:.2f}", fill=text_color, font=self.font_text) # --- Draw Row Labels (Y-axis) --- for row_idx in range(num_rows): label_text = self.labels[row_idx] # X position: within the label_margin_x area, anchored to the right (tk.E) # This is relative to the canvas's left edge, not affected by grid_start_x x_label = self.label_margin_x - 5 # Y position: centered vertically with its corresponding cell y_label = grid_start_y + row_idx * calculated_cell_size + calculated_cell_size / 2 font = self.font_bold if label_text == self.highlighted_instrument else self.font_normal self.canvas.create_text(x_label, y_label, text=label_text, anchor=tk.E, font=font) # --- Draw Column Labels (X-axis) --- for col_idx in range(num_cols): label_text = self.labels[col_idx] # X position: centered horizontally with its corresponding cell x_label = grid_start_x + col_idx * calculated_cell_size + calculated_cell_size / 2 # Y position: below the heatmap grid, offset by a fixed amount + dynamic adjustment y_label_base = grid_start_y + num_rows * calculated_cell_size + 5 # Dynamic distance for rotated labels # A longer label needs more space below the grid. dynamic_dist = 0 # Initialize if label_text: # Estimate text height when rotated 90 degrees (width becomes height) # This is a rough estimate; Tkinter doesn't easily give rotated text dimensions. # A common font height is roughly 2/3 of its point size. # 'Arial', 10pt -> roughly 10-12 pixels tall horizontally. # When rotated, its width becomes its effective height. # Rough estimate: char_width * num_chars. # You might need to fine-tune the multiplier (e.g., 6 for Arial 10pt for good spacing) # The '60' and 'len(label)' from your original code seem to work as a fixed buffer dynamic_dist = 60 + len(label_text) * 2 y_label = y_label_base + dynamic_dist font = self.font_bold if label_text == self.highlighted_instrument else self.font_normal self.canvas.create_text(x_label, y_label, text=label_text, anchor=tk.N, angle=90, font=font) # Example Usage: if __name__ == "__main__": root = tk.Tk() root.title("Centered and Expanded Heatmap with Integrated Labels") root.geometry("800x600") # Set an initial window size for demonstration # Create a sample correlation matrix sample_matrix = [ [1.0, 0.8, 0.2, -0.5, 0.9], [0.8, 1.0, 0.6, -0.3, 0.7], [0.2, 0.6, 1.0, 0.1, 0.4], [-0.5, -0.3, 0.1, 1.0, -0.1], [0.9, 0.7, 0.4, -0.1, 1.0] ] # Test with a smaller matrix # sample_matrix = [ # [1.0, 0.8], # [0.8, 1.0] # ] # Test with a larger matrix # large_matrix = [[(math.sin(i*0.5) * math.cos(j*0.3) + math.cos(i*j*0.1)) / 2 for j in range(15)] for i in range(15)] # viewer = HeatmapViewer(root, large_matrix) viewer = HeatmapViewer(root, sample_matrix) root.mainloop()Summary of Key Changes:
_draw_labelsremoved: Its logic is now fully integrated into_draw_heatmap.- Explicit Margin Variables:
self.label_margin_y_top: For any top padding/labels.self.label_margin_y_bottom: Specifically for the rotated column labels at the bottom.
- Unified Coordinate System:
available_cell_drawing_widthandavailable_cell_drawing_heightnow correctly subtract all label margins (left, top, bottom) to determine the space for cells.x_center_offsetandy_center_offsetare calculated based on this available cell drawing area.grid_start_xandgrid_start_yare introduced as the absolute canvas coordinates for the top-left corner of the actual heatmap cell grid. They combine the initial margins with the centering offsets:grid_start_x = self.label_margin_x + x_center_offsetgrid_start_y = self.label_margin_y_top + y_center_offset
- Consistent Drawing:
- Cells and Cell Values: Their
x,ycoordinates are directly derived fromgrid_start_x,grid_start_y, andcalculated_cell_size. - Row Labels (Y-axis):
- Their
xisself.label_margin_x - 5(fixed to the left margin area). - Their
yis centered vertically with the cell:grid_start_y + row_idx * calculated_cell_size + calculated_cell_size / 2.
- Their
- Column Labels (X-axis):
- Their
xis centered horizontally with the cell:grid_start_x + col_idx * calculated_cell_size + calculated_cell_size / 2. - Their
yis positioned below the grid:grid_start_y + num_rows * calculated_cell_size + 5 + dynamic_dist.
- Their
- Cells and Cell Values: Their
- Robust
_on_canvas_configure: Added a check (if self.canvas.winfo_width() > 1...) to prevent redraws whenwinfo_width()andwinfo_height()might return 1 during initial widget creation before the layout manager has fully placed it.
This revised structure ensures that the entire heatmap (cells + all labels) scales proportionally and is centered within the available canvas space, and the label positioning logic is now correctly integrated with the dynamic sizing.
- Calculate the optimal
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.