Skip to content

Commit

Permalink
fix mpl figure tick color
Browse files Browse the repository at this point in the history
  • Loading branch information
hanjinliu committed Jan 24, 2024
1 parent 3d9af77 commit d58e407
Show file tree
Hide file tree
Showing 5 changed files with 17 additions and 115 deletions.
1 change: 0 additions & 1 deletion tabulous/_magicgui/_dialog.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
7 changes: 4 additions & 3 deletions tabulous/_psygnal/_slots.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down Expand Up @@ -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
Expand All @@ -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}")
Expand Down
38 changes: 13 additions & 25 deletions tabulous/_qt/_plot/_widget.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -11,7 +10,6 @@
from matplotlib.axes import Axes
from matplotlib.artist import Artist

from seaborn.axisgrid import Grid
from tabulous.widgets import TableBase


Expand Down Expand Up @@ -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__()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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."""

Expand Down
50 changes: 0 additions & 50 deletions tabulous/_qt/_table/_spreadsheet.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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 == "":
Expand Down
36 changes: 0 additions & 36 deletions tabulous/widgets/_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down

0 comments on commit d58e407

Please sign in to comment.