Skip to content

TYP: pandas/plotting annotations from pandas-stubs #47827

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jul 25, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ repos:
types: [python]
stages: [manual]
additional_dependencies: &pyright_dependencies
- [email protected].258
- [email protected].262
- id: pyright_reportGeneralTypeIssues
name: pyright reportGeneralTypeIssues
entry: pyright --skipunannotated -p pyright_reportGeneralTypeIssues.json
Expand Down
2 changes: 1 addition & 1 deletion pandas/core/arrays/arrow/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -444,7 +444,7 @@ def dropna(self: ArrowExtensionArrayT) -> ArrowExtensionArrayT:
else:
return type(self)(pc.drop_null(self._data))

def isin(self: ArrowExtensionArrayT, values) -> npt.NDArray[np.bool_]:
def isin(self, values) -> npt.NDArray[np.bool_]:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why make this change?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This TypeVar is useless (my local pyright version complained about it). I'll bump pyright on the CI

if pa_version_under2p0:
fallback_performancewarning(version="2")
return super().isin(values)
Expand Down
58 changes: 31 additions & 27 deletions pandas/plotting/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
from pandas.core.base import PandasObject

if TYPE_CHECKING:
from matplotlib.axes import Axes

from pandas import DataFrame


Expand Down Expand Up @@ -463,16 +465,16 @@ def hist_frame(
@Substitution(backend="")
@Appender(_boxplot_doc)
def boxplot(
data,
column=None,
by=None,
ax=None,
fontsize=None,
rot=0,
grid=True,
figsize=None,
layout=None,
return_type=None,
data: DataFrame,
column: str | list[str] | None = None,
by: str | list[str] | None = None,
ax: Axes | None = None,
fontsize: float | str | None = None,
rot: int = 0,
grid: bool = True,
figsize: tuple[float, float] | None = None,
layout: tuple[int, int] | None = None,
return_type: str | None = None,
**kwargs,
):
plot_backend = _get_plot_backend("matplotlib")
Expand All @@ -499,8 +501,8 @@ def boxplot_frame(
by=None,
ax=None,
fontsize=None,
rot=0,
grid=True,
rot: int = 0,
grid: bool = True,
figsize=None,
layout=None,
return_type=None,
Expand All @@ -525,16 +527,16 @@ def boxplot_frame(

def boxplot_frame_groupby(
grouped,
subplots=True,
subplots: bool = True,
column=None,
fontsize=None,
rot=0,
grid=True,
rot: int = 0,
grid: bool = True,
ax=None,
figsize=None,
layout=None,
sharex=False,
sharey=True,
sharex: bool = False,
sharey: bool = True,
backend=None,
**kwargs,
):
Expand Down Expand Up @@ -1041,7 +1043,7 @@ def __call__(self, *args, **kwargs):
)
@Substitution(kind="line")
@Appender(_bar_or_line_doc)
def line(self, x=None, y=None, **kwargs):
def line(self, x=None, y=None, **kwargs) -> PlotAccessor:
"""
Plot Series or DataFrame as lines.

Expand Down Expand Up @@ -1128,7 +1130,7 @@ def line(self, x=None, y=None, **kwargs):
)
@Substitution(kind="bar")
@Appender(_bar_or_line_doc)
def bar(self, x=None, y=None, **kwargs):
def bar(self, x=None, y=None, **kwargs) -> PlotAccessor:
"""
Vertical bar plot.

Expand Down Expand Up @@ -1214,7 +1216,7 @@ def bar(self, x=None, y=None, **kwargs):
)
@Substitution(kind="bar")
@Appender(_bar_or_line_doc)
def barh(self, x=None, y=None, **kwargs):
def barh(self, x=None, y=None, **kwargs) -> PlotAccessor:
"""
Make a horizontal bar plot.

Expand All @@ -1226,7 +1228,7 @@ def barh(self, x=None, y=None, **kwargs):
"""
return self(kind="barh", x=x, y=y, **kwargs)

def box(self, by=None, **kwargs):
def box(self, by=None, **kwargs) -> PlotAccessor:
r"""
Make a box plot of the DataFrame columns.

Expand Down Expand Up @@ -1293,7 +1295,7 @@ def box(self, by=None, **kwargs):
"""
return self(kind="box", by=by, **kwargs)

def hist(self, by=None, bins=10, **kwargs):
def hist(self, by=None, bins: int = 10, **kwargs) -> PlotAccessor:
"""
Draw one histogram of the DataFrame's columns.

Expand Down Expand Up @@ -1355,7 +1357,7 @@ def hist(self, by=None, bins=10, **kwargs):
"""
return self(kind="hist", by=by, bins=bins, **kwargs)

def kde(self, bw_method=None, ind=None, **kwargs):
def kde(self, bw_method=None, ind=None, **kwargs) -> PlotAccessor:
"""
Generate Kernel Density Estimate plot using Gaussian kernels.

Expand Down Expand Up @@ -1465,7 +1467,7 @@ def kde(self, bw_method=None, ind=None, **kwargs):

density = kde

def area(self, x=None, y=None, **kwargs):
def area(self, x=None, y=None, **kwargs) -> PlotAccessor:
"""
Draw a stacked area plot.

Expand Down Expand Up @@ -1538,7 +1540,7 @@ def area(self, x=None, y=None, **kwargs):
"""
return self(kind="area", x=x, y=y, **kwargs)

def pie(self, **kwargs):
def pie(self, **kwargs) -> PlotAccessor:
"""
Generate a pie plot.

Expand Down Expand Up @@ -1593,7 +1595,7 @@ def pie(self, **kwargs):
raise ValueError("pie requires either y column or 'subplots=True'")
return self(kind="pie", **kwargs)

def scatter(self, x, y, s=None, c=None, **kwargs):
def scatter(self, x, y, s=None, c=None, **kwargs) -> PlotAccessor:
"""
Create a scatter plot with varying marker point size and color.

Expand Down Expand Up @@ -1699,7 +1701,9 @@ def scatter(self, x, y, s=None, c=None, **kwargs):

return self(kind="scatter", x=x, y=y, **kwargs)

def hexbin(self, x, y, C=None, reduce_C_function=None, gridsize=None, **kwargs):
def hexbin(
self, x, y, C=None, reduce_C_function=None, gridsize=None, **kwargs
) -> PlotAccessor:
"""
Generate a hexagonal binning plot.

Expand Down
22 changes: 11 additions & 11 deletions pandas/plotting/_matplotlib/boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ class BP(NamedTuple):
ax: Axes
lines: dict[str, list[Line2D]]

def __init__(self, data, return_type="axes", **kwargs) -> None:
def __init__(self, data, return_type: str = "axes", **kwargs) -> None:
# Do not call LinePlot.__init__ which may fill nan
if return_type not in self._valid_return_types:
raise ValueError("return_type must be {None, 'axes', 'dict', 'both'}")
Expand Down Expand Up @@ -117,7 +117,7 @@ def _validate_color_args(self):
def _get_colors(self, num_colors=None, color_kwds="color"):
pass

def maybe_color_bp(self, bp):
def maybe_color_bp(self, bp) -> None:
if isinstance(self.color, dict):
boxes = self.color.get("boxes", self._boxes_c)
whiskers = self.color.get("whiskers", self._whiskers_c)
Expand Down Expand Up @@ -292,8 +292,8 @@ def boxplot(
by=None,
ax=None,
fontsize=None,
rot=0,
grid=True,
rot: int = 0,
grid: bool = True,
figsize=None,
layout=None,
return_type=None,
Expand Down Expand Up @@ -443,8 +443,8 @@ def boxplot_frame(
by=None,
ax=None,
fontsize=None,
rot=0,
grid=True,
rot: int = 0,
grid: bool = True,
figsize=None,
layout=None,
return_type=None,
Expand All @@ -471,16 +471,16 @@ def boxplot_frame(

def boxplot_frame_groupby(
grouped,
subplots=True,
subplots: bool = True,
column=None,
fontsize=None,
rot=0,
grid=True,
rot: int = 0,
grid: bool = True,
ax=None,
figsize=None,
layout=None,
sharex=False,
sharey=True,
sharex: bool = False,
sharey: bool = True,
**kwds,
):
if subplots is True:
Expand Down
42 changes: 22 additions & 20 deletions pandas/plotting/_matplotlib/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import functools
from typing import (
Any,
Final,
Iterator,
cast,
)

Expand Down Expand Up @@ -56,14 +58,14 @@
import pandas.core.tools.datetimes as tools

# constants
HOURS_PER_DAY = 24.0
MIN_PER_HOUR = 60.0
SEC_PER_MIN = 60.0
HOURS_PER_DAY: Final = 24.0
MIN_PER_HOUR: Final = 60.0
SEC_PER_MIN: Final = 60.0

SEC_PER_HOUR = SEC_PER_MIN * MIN_PER_HOUR
SEC_PER_DAY = SEC_PER_HOUR * HOURS_PER_DAY
SEC_PER_HOUR: Final = SEC_PER_MIN * MIN_PER_HOUR
SEC_PER_DAY: Final = SEC_PER_HOUR * HOURS_PER_DAY

MUSEC_PER_DAY = 10**6 * SEC_PER_DAY
MUSEC_PER_DAY: Final = 10**6 * SEC_PER_DAY

_mpl_units = {} # Cache for units overwritten by us

Expand Down Expand Up @@ -94,7 +96,7 @@ def wrapper(*args, **kwargs):


@contextlib.contextmanager
def pandas_converters():
def pandas_converters() -> Iterator[None]:
"""
Context manager registering pandas' converters for a plot.

Expand All @@ -115,7 +117,7 @@ def pandas_converters():
deregister()


def register():
def register() -> None:
pairs = get_pairs()
for type_, cls in pairs:
# Cache previous converter if present
Expand All @@ -126,7 +128,7 @@ def register():
units.registry[type_] = cls()


def deregister():
def deregister() -> None:
# Renamed in pandas.plotting.__init__
for type_, cls in get_pairs():
# We use type to catch our classes directly, no inheritance
Expand Down Expand Up @@ -187,7 +189,7 @@ class TimeFormatter(Formatter):
def __init__(self, locs) -> None:
self.locs = locs

def __call__(self, x, pos=0) -> str:
def __call__(self, x, pos: int = 0) -> str:
"""
Return the time of day as a formatted string.

Expand Down Expand Up @@ -339,7 +341,7 @@ def axisinfo(unit: tzinfo | None, axis) -> units.AxisInfo:


class PandasAutoDateFormatter(dates.AutoDateFormatter):
def __init__(self, locator, tz=None, defaultfmt="%Y-%m-%d") -> None:
def __init__(self, locator, tz=None, defaultfmt: str = "%Y-%m-%d") -> None:
dates.AutoDateFormatter.__init__(self, locator, tz, defaultfmt)


Expand Down Expand Up @@ -937,12 +939,12 @@ class TimeSeries_DateLocator(Locator):
def __init__(
self,
freq: BaseOffset,
minor_locator=False,
dynamic_mode=True,
base=1,
quarter=1,
month=1,
day=1,
minor_locator: bool = False,
dynamic_mode: bool = True,
base: int = 1,
quarter: int = 1,
month: int = 1,
day: int = 1,
plot_obj=None,
) -> None:
freq = to_offset(freq)
Expand Down Expand Up @@ -1053,7 +1055,7 @@ def _set_default_format(self, vmin, vmax):
self.formatdict = {x: f for (x, _, _, f) in format}
return self.formatdict

def set_locs(self, locs):
def set_locs(self, locs) -> None:
"""Sets the locations of the ticks"""
# don't actually use the locs. This is just needed to work with
# matplotlib. Force to use vmin, vmax
Expand All @@ -1068,7 +1070,7 @@ def set_locs(self, locs):
(vmin, vmax) = (vmax, vmin)
self._set_default_format(vmin, vmax)

def __call__(self, x, pos=0) -> str:
def __call__(self, x, pos: int = 0) -> str:

if self.formatdict is None:
return ""
Expand Down Expand Up @@ -1103,7 +1105,7 @@ def format_timedelta_ticks(x, pos, n_decimals: int) -> str:
s = f"{int(d):d} days {s}"
return s

def __call__(self, x, pos=0) -> str:
def __call__(self, x, pos: int = 0) -> str:
(vmin, vmax) = tuple(self.axis.get_view_interval())
n_decimals = int(np.ceil(np.log10(100 * 10**9 / abs(vmax - vmin))))
if n_decimals > 9:
Expand Down
Loading