From d58e4070e1a0a511fd7631b6d024dcab00d1e470 Mon Sep 17 00:00:00 2001 From: Hanjin Liu Date: Wed, 24 Jan 2024 20:35:58 +0900 Subject: [PATCH] fix mpl figure tick color --- tabulous/_magicgui/_dialog.py | 1 - tabulous/_psygnal/_slots.py | 7 ++-- tabulous/_qt/_plot/_widget.py | 38 ++++++++-------------- tabulous/_qt/_table/_spreadsheet.py | 50 ----------------------------- tabulous/widgets/_table.py | 36 --------------------- 5 files changed, 17 insertions(+), 115 deletions(-) diff --git a/tabulous/_magicgui/_dialog.py b/tabulous/_magicgui/_dialog.py index 50411e0b..3d9bbfa0 100644 --- a/tabulous/_magicgui/_dialog.py +++ b/tabulous/_magicgui/_dialog.py @@ -110,7 +110,6 @@ def _runner(parent=None, **param_options): plt = QtMplPlotCanvas(style=style, pickable=False) if bg: plt.set_background_color(bg) - dlg.native.layout().addWidget(plt) dlg.height = 400 dlg.width = 280 diff --git a/tabulous/_psygnal/_slots.py b/tabulous/_psygnal/_slots.py index 396018b9..da936cb0 100644 --- a/tabulous/_psygnal/_slots.py +++ b/tabulous/_psygnal/_slots.py @@ -109,6 +109,7 @@ def __init__(self, objs: list): self._objs = objs def eval(self, ns: dict[str, Any], ranges: MultiRectRange): + """Evaluate this expression.""" return self.eval_and_format(ns, ranges)[0] def eval_and_format(self, ns: dict[str, Any], ranges: MultiRectRange): @@ -254,8 +255,8 @@ def from_table( # check if the expression contains `N` for ast_obj in ast.walk(ast.parse(expr)): if isinstance(ast_obj, ast.Name) and ast_obj.id == "N": - # By this, this slot will be evaluated when the number of - # columns changed. + # By this, this slot will be evaluated when the number of columns + # changed. ranges.append((slice(BIG, BIG + 1), slice(None))) break # func pos range @@ -280,7 +281,7 @@ def evaluate(self) -> EvalResult: ns = dict(qviewer._namespace) else: ns = {"np": np, "pd": pd} - ns.update(df=df, N=RowCountGetter(qtable)) + ns.update(df=df, N=RowCountGetter(qtable), DF=df.iloc) try: out, _expr = self._expr.eval_and_format(ns, self.range) logger.debug(f"Evaluated at {self.pos!r}") diff --git a/tabulous/_qt/_plot/_widget.py b/tabulous/_qt/_plot/_widget.py index 9775db7e..671b8d25 100644 --- a/tabulous/_qt/_plot/_widget.py +++ b/tabulous/_qt/_plot/_widget.py @@ -1,6 +1,5 @@ from __future__ import annotations -from functools import wraps from typing import TYPE_CHECKING import weakref from qtpy import QtWidgets as QtW, QtGui, QtCore @@ -11,7 +10,6 @@ from matplotlib.axes import Axes from matplotlib.artist import Artist - from seaborn.axisgrid import Grid from tabulous.widgets import TableBase @@ -44,8 +42,10 @@ def __init__( mpl.use(backend) fig: Figure + mgr = fig.canvas.manager canvas = InteractiveFigureCanvas(fig) self.canvas = canvas + canvas.manager = mgr self.figure = fig super().__init__() @@ -80,6 +80,17 @@ def cla(self) -> None: if self._style: with plt.style.context(self._style): self.ax.cla() + # NOTE: for some reason, the color of the ticks and tick labels will + # be initialized. + color = self.ax.spines["bottom"].get_edgecolor() + for line in self.ax.get_xticklines(): + line.set_color(color) + for line in self.ax.get_yticklines(): + line.set_color(color) + for text in self.ax.get_xticklabels(): + text.set_color(color) + for text in self.ax.get_yticklabels(): + text.set_color(color) else: self.ax.cla() return None @@ -164,29 +175,6 @@ def set_background_color(self, color: str): self.canvas.draw() -def _use_seaborn_grid(f): - """ - Some seaborn plot functions will create a new figure. - This decorator provides a common way to update figure canvas in the widget. - """ - - @wraps(f) - def func(self: QtMplPlotCanvas, *args, **kwargs): - import matplotlib as mpl - - backend = mpl.get_backend() - try: - mpl.use("Agg") - grid: Grid = f(self, *args, **kwargs) - finally: - mpl.use(backend) - - self._reset_canvas(grid.figure) - return grid - - return func - - class QMplEditor(QtW.QTabWidget): """Editor widget for matplotlib artists.""" diff --git a/tabulous/_qt/_table/_spreadsheet.py b/tabulous/_qt/_table/_spreadsheet.py index 5387e469..7d887465 100644 --- a/tabulous/_qt/_table/_spreadsheet.py +++ b/tabulous/_qt/_table/_spreadsheet.py @@ -21,8 +21,6 @@ from tabulous._text_formatter import DefaultFormatter from tabulous import _pd_index -if TYPE_CHECKING: - from magicgui.widgets._bases import ValueWidget # More rows/columns will be displayed _STRING_DTYPE = get_dtype("string") @@ -844,54 +842,6 @@ def _remove_columns( self.setSelections([(slice(0, self._data_raw.shape[0]), slice(col, col + 1))]) return None - @QMutableSimpleTable._mgr.interface - def _set_widget_at_index(self, r: int, c: int, widget: ValueWidget | None) -> None: - index = self.model().index(r, c) - if wdt := self._qtable_view.indexWidget(index): - try: - self.itemChangedSignal.disconnect(wdt._tabulous_callback) - except TypeError: - pass - wdt.close() - - if widget is None: - # equivalent to delete the widget - return None - - if widget.widget_type in ("CheckBox", "RadioButton"): - - def converter(x): - return x != "False" - - elif widget.widget_type in ("SpinBox", "Slider"): - converter = int - elif widget.widget_type in ("FloatSpinBox", "FloatSlider"): - converter = float - else: - converter = str - - def _sig(): - with widget.changed.blocked(): - val = self.model().df.iat[r, c] - try: - widget.value = converter(val) - except Exception: - self.setDataFrameValue(r, c, str(widget.value)) - raise - - if self.model().df.iat[r, c] != "": - _sig() - widget.native._tabulous_callback = _sig - self.itemChangedSignal.connect(_sig) - widget.changed.connect(lambda val: self.setDataFrameValue(r, c, str(val))) - self._qtable_view.setIndexWidget(index, widget.native) - - @_set_widget_at_index.server - def _set_widget_at_index(self, r: int, c: int, widget: ValueWidget): - index = self.model().index(r, c) - wdt = self._qtable_view.indexWidget(index) - return arguments(r, c, getattr(wdt, "_magic_widget", None)) - def setVerticalHeaderValue(self, index: int, value: Any) -> None: """Set value of the table vertical header and DataFrame at the index.""" if value == "": diff --git a/tabulous/widgets/_table.py b/tabulous/widgets/_table.py index 052136cc..727616a3 100644 --- a/tabulous/widgets/_table.py +++ b/tabulous/widgets/_table.py @@ -784,15 +784,6 @@ def _create_backend(self, data: pd.DataFrame) -> QSpreadSheet: return QSpreadSheet(data=data) - def add_item_widget(self, row: int, column: int, widget): - """Add a widget to a cell.""" - warnings.warn( - "`add_item_widget` is deprecated because its behavior is not stable. " - "Will be removed in the future. Use side area or dock widget instead.", - DeprecationWarning, - ) - return self._qwidget._set_widget_at_index(row, column, widget) - def _install_actions(self): from tabulous import commands as cmds @@ -941,33 +932,6 @@ def running(self, value: bool) -> None: return self._qwidget.setRunning(value) -# deprecations - - -def foreground_colormap(self: TableBase, *args, **kwargs): - """Deprecated method.""" - warnings.warn( - "Method `table.foreground_colormap` is deprecated. " - "Use `table.text_color.set` instead.", - DeprecationWarning, - ) - return self.text_color.set(*args, **kwargs) - - -def background_colormap(self: TableBase, *args, **kwargs): - """Deprecated method.""" - warnings.warn( - "Method `table.background_colormap` is deprecated. " - "Use `table.background_color.set` instead.", - DeprecationWarning, - ) - return self.background_color.set(*args, **kwargs) - - -TableBase.foreground_colormap = foreground_colormap -TableBase.background_colormap = background_colormap - - def is_polars_data_frame(data): if _get_module(data) == "polars": import polars as pl