Skip to content

CLN: plotting #56091

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 3 commits into from
Nov 21, 2023
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
3 changes: 2 additions & 1 deletion pandas/plotting/_matplotlib/boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from pandas.util._exceptions import find_stack_level

from pandas.core.dtypes.common import is_dict_like
from pandas.core.dtypes.generic import ABCSeries
from pandas.core.dtypes.missing import remove_na_arraylike

import pandas as pd
Expand Down Expand Up @@ -362,7 +363,7 @@ def boxplot(
if return_type not in BoxPlot._valid_return_types:
raise ValueError("return_type must be {'axes', 'dict', 'both'}")

if isinstance(data, pd.Series):
if isinstance(data, ABCSeries):
data = data.to_frame("x")
column = "x"

Expand Down
41 changes: 20 additions & 21 deletions pandas/plotting/_matplotlib/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -504,7 +504,7 @@ def generate(self) -> None:
self._adorn_subplots(fig)

for ax in self.axes:
self._post_plot_logic_common(ax, self.data)
self._post_plot_logic_common(ax)
self._post_plot_logic(ax, self.data)

@final
Expand Down Expand Up @@ -697,7 +697,7 @@ def _compute_plot_data(self):
if is_empty:
raise TypeError("no numeric data to plot")

self.data = numeric_data.apply(self._convert_to_ndarray)
self.data = numeric_data.apply(type(self)._convert_to_ndarray)

def _make_plot(self, fig: Figure):
raise AbstractMethodError(self)
Expand All @@ -714,21 +714,29 @@ def _add_table(self) -> None:
tools.table(ax, data)

@final
def _post_plot_logic_common(self, ax: Axes, data) -> None:
def _post_plot_logic_common(self, ax: Axes) -> None:
"""Common post process for each axes"""
if self.orientation == "vertical" or self.orientation is None:
self._apply_axis_properties(ax.xaxis, rot=self.rot, fontsize=self.fontsize)
self._apply_axis_properties(ax.yaxis, fontsize=self.fontsize)
type(self)._apply_axis_properties(
ax.xaxis, rot=self.rot, fontsize=self.fontsize
)
type(self)._apply_axis_properties(ax.yaxis, fontsize=self.fontsize)

if hasattr(ax, "right_ax"):
self._apply_axis_properties(ax.right_ax.yaxis, fontsize=self.fontsize)
type(self)._apply_axis_properties(
ax.right_ax.yaxis, fontsize=self.fontsize
)

elif self.orientation == "horizontal":
self._apply_axis_properties(ax.yaxis, rot=self.rot, fontsize=self.fontsize)
self._apply_axis_properties(ax.xaxis, fontsize=self.fontsize)
type(self)._apply_axis_properties(
ax.yaxis, rot=self.rot, fontsize=self.fontsize
)
type(self)._apply_axis_properties(ax.xaxis, fontsize=self.fontsize)

if hasattr(ax, "right_ax"):
self._apply_axis_properties(ax.right_ax.yaxis, fontsize=self.fontsize)
type(self)._apply_axis_properties(
ax.right_ax.yaxis, fontsize=self.fontsize
)
else: # pragma no cover
raise ValueError

Expand Down Expand Up @@ -799,8 +807,9 @@ def _adorn_subplots(self, fig: Figure):
self.axes[0].set_title(self.title)

@final
@staticmethod
def _apply_axis_properties(
self, axis: Axis, rot=None, fontsize: int | None = None
axis: Axis, rot=None, fontsize: int | None = None
) -> None:
"""
Tick creation within matplotlib is reasonably expensive and is
Expand Down Expand Up @@ -1028,16 +1037,6 @@ def _get_ax(self, i: int):
ax.get_yaxis().set_visible(True)
return ax

@final
@classmethod
def get_default_ax(cls, ax) -> None:
import matplotlib.pyplot as plt

if ax is None and len(plt.get_fignums()) > 0:
with plt.rc_context():
ax = plt.gca()
ax = cls._get_ax_layer(ax)

@final
def on_right(self, i: int):
if isinstance(self.secondary_y, bool):
Expand Down Expand Up @@ -1192,7 +1191,7 @@ def match_labels(data, e):
@final
def _get_errorbars(
self, label=None, index=None, xerr: bool = True, yerr: bool = True
):
) -> dict[str, Any]:
errors = {}

for kw, flag in zip(["xerr", "yerr"], [xerr, yerr]):
Expand Down
13 changes: 8 additions & 5 deletions pandas/plotting/_matplotlib/groupby.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@
from pandas.core.dtypes.missing import remove_na_arraylike

from pandas import (
DataFrame,
MultiIndex,
Series,
concat,
)

Expand All @@ -20,6 +18,11 @@

from pandas._typing import IndexLabel

from pandas import (
DataFrame,
Series,
)


def create_iter_data_given_by(
data: DataFrame, kind: str = "hist"
Expand Down Expand Up @@ -48,10 +51,10 @@ def create_iter_data_given_by(

>>> import numpy as np
>>> tuples = [('h1', 'a'), ('h1', 'b'), ('h2', 'a'), ('h2', 'b')]
>>> mi = MultiIndex.from_tuples(tuples)
>>> mi = pd.MultiIndex.from_tuples(tuples)
>>> value = [[1, 3, np.nan, np.nan],
... [3, 4, np.nan, np.nan], [np.nan, np.nan, 5, 6]]
>>> data = DataFrame(value, columns=mi)
>>> data = pd.DataFrame(value, columns=mi)
>>> create_iter_data_given_by(data)
{'h1': h1
a b
Expand Down Expand Up @@ -104,7 +107,7 @@ def reconstruct_data_with_by(
Examples
--------
>>> d = {'h': ['h1', 'h1', 'h2'], 'a': [1, 3, 5], 'b': [3, 4, 6]}
>>> df = DataFrame(d)
>>> df = pd.DataFrame(d)
>>> reconstruct_data_with_by(df, by='h', cols=['a', 'b'])
h1 h2
a b a b
Expand Down
12 changes: 6 additions & 6 deletions pandas/plotting/_matplotlib/hist.py
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ def _make_plot(self, fig: Figure) -> None:
kwds.pop("color")

if self.weights is not None:
kwds["weights"] = self._get_column_weights(self.weights, i, y)
kwds["weights"] = type(self)._get_column_weights(self.weights, i, y)

y = reformat_hist_y_given_by(y, self.by)

Expand Down Expand Up @@ -284,15 +284,15 @@ def _plot( # type: ignore[override]

def _make_plot_keywords(self, kwds: dict[str, Any], y: np.ndarray) -> None:
kwds["bw_method"] = self.bw_method
kwds["ind"] = self._get_ind(y, ind=self.ind)
kwds["ind"] = type(self)._get_ind(y, ind=self.ind)

def _post_plot_logic(self, ax: Axes, data) -> None:
ax.set_ylabel("Density")


def _grouped_plot(
plotf,
data,
data: Series | DataFrame,
column=None,
by=None,
numeric_only: bool = True,
Expand Down Expand Up @@ -335,7 +335,7 @@ def _grouped_plot(


def _grouped_hist(
data,
data: Series | DataFrame,
column=None,
by=None,
ax=None,
Expand Down Expand Up @@ -417,7 +417,7 @@ def plot_group(group, ax) -> None:


def hist_series(
self,
self: Series,
by=None,
ax=None,
grid: bool = True,
Expand Down Expand Up @@ -495,7 +495,7 @@ def hist_series(


def hist_frame(
data,
data: DataFrame,
column=None,
by=None,
grid: bool = True,
Expand Down