Skip to content

Commit

Permalink
Set the aspect ratio of images automatically based on their shape
Browse files Browse the repository at this point in the history
Anything with an aspect ratio >4 gets a dynamic aspect ratio by default.
  • Loading branch information
JamesWrigley committed Jul 7, 2023
1 parent f9a0aeb commit 0f76db7
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions damnit/gui/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import pandas as pd
from pandas.api.types import is_numeric_dtype

from PyQt5.QtCore import Qt
from PyQt5 import QtCore, QtWidgets
from PyQt5.QtWidgets import QMessageBox

Expand Down Expand Up @@ -92,6 +93,13 @@ def __init__(
QtCore.Qt.LayoutDirection.RightToLeft
)

self._dynamic_aspect_checkbox = QtWidgets.QCheckBox("Dynamic aspect ratio")
self._dynamic_aspect_checkbox.setCheckState(Qt.Unchecked)
self._dynamic_aspect_checkbox.setLayoutDirection(Qt.RightToLeft)
self._dynamic_aspect_checkbox.stateChanged.connect(
lambda state: self.set_dynamic_aspect(state == Qt.Checked)
)

self._display_annotations_checkbox = QtWidgets.QCheckBox(
"Display hover annotations", self
)
Expand Down Expand Up @@ -122,6 +130,8 @@ def __init__(

layout.addLayout(h1_layout)
layout.addLayout(h2_layout)
if image is not None:
layout.addWidget(self._dynamic_aspect_checkbox)

layout.addWidget(self._navigation_toolbar)

Expand All @@ -130,6 +140,13 @@ def __init__(
self._panmanager = PanManager(self.figure, MouseButton.LEFT)

self.update_canvas(x, y, image, legend=legend)

# Take a guess at a good aspect ratio if it's an image
if image is not None:
aspect_ratio = max(image.shape[:2]) / min(image.shape[:2])
if aspect_ratio > 4:
self._dynamic_aspect_checkbox.setCheckState(Qt.Checked)

self.figure.tight_layout()

def toggle_annotations(self, state):
Expand Down Expand Up @@ -163,6 +180,11 @@ def autoscale(self, x_min, x_max, y_min, y_max, margin=0.05):
y_max = y_max + y_range * margin
self._axis.set_ylim((y_min, y_max))

def set_dynamic_aspect(self, is_dynamic):
aspect = "auto" if is_dynamic else "equal"
self._axis.set_aspect(aspect)
self.figure.canvas.draw()

def update_canvas(self, xs=None, ys=None, image=None, legend=None, series_names=["default"]):
cmap = mpl_cm.get_cmap("tab20")
self._nan_warning_label.hide()
Expand Down

0 comments on commit 0f76db7

Please sign in to comment.