Skip to content

CLN - Change string formatting in plotting #29781

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, 2019
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
39 changes: 17 additions & 22 deletions pandas/plotting/_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -736,26 +736,23 @@ def _get_call_args(backend_name, data, args, kwargs):
]
else:
raise TypeError(
(
"Called plot accessor for type {}, expected Series or DataFrame"
).format(type(data).__name__)
f"Called plot accessor for type {type(data).__name__}, "
"expected Series or DataFrame"
)

if args and isinstance(data, ABCSeries):
positional_args = str(args)[1:-1]
keyword_args = ", ".join(
f"{name}={value!r}" for (name, default), value in zip(arg_def, args)
)
msg = (
"`Series.plot()` should not be called with positional "
"arguments, only keyword arguments. The order of "
"positional arguments will change in the future. "
"Use `Series.plot({})` instead of `Series.plot({})`."
)
positional_args = str(args)[1:-1]
keyword_args = ", ".join(
"{}={!r}".format(name, value)
for (name, default), value in zip(arg_def, args)
)
warnings.warn(
msg.format(keyword_args, positional_args), FutureWarning, stacklevel=3
f"Use `Series.plot({keyword_args})` instead of "
f"`Series.plot({positional_args})`."
)
warnings.warn(msg, FutureWarning, stacklevel=3)

pos_args = {name: value for value, (name, _) in zip(args, arg_def)}
if backend_name == "pandas.plotting._matplotlib":
Expand All @@ -782,7 +779,7 @@ def __call__(self, *args, **kwargs):
return plot_backend.plot(self._parent, x=x, y=y, kind=kind, **kwargs)

if kind not in self._all_kinds:
raise ValueError("{} is not a valid plot kind".format(kind))
raise ValueError(f"{kind} is not a valid plot kind")

# The original data structured can be transformed before passed to the
# backend. For example, for DataFrame is common to set the index as the
Expand All @@ -796,14 +793,13 @@ def __call__(self, *args, **kwargs):
if isinstance(data, ABCDataFrame):
return plot_backend.plot(data, x=x, y=y, kind=kind, **kwargs)
else:
raise ValueError(
("plot kind {} can only be used for data frames").format(kind)
)
raise ValueError(f"plot kind {kind} can only be used for data frames")
elif kind in self._series_kinds:
if isinstance(data, ABCDataFrame):
if y is None and kwargs.get("subplots") is False:
msg = "{} requires either y column or 'subplots=True'"
raise ValueError(msg.format(kind))
raise ValueError(
f"{kind} requires either y column or 'subplots=True'"
)
elif y is not None:
if is_integer(y) and not data.columns.holds_integer():
y = data.columns[y]
Expand Down Expand Up @@ -1639,12 +1635,11 @@ def _find_backend(backend: str):
_backends[backend] = module
return module

msg = (
"Could not find plotting backend '{name}'. Ensure that you've installed the "
"package providing the '{name}' entrypoint, or that the package has a"
raise ValueError(
f"Could not find plotting backend '{backend}'. Ensure that you've installed "
f"the package providing the '{backend}' entrypoint, or that the package has a "
"top-level `.plot` method."
)
raise ValueError(msg.format(name=backend))


def _get_plot_backend(backend=None):
Expand Down
12 changes: 5 additions & 7 deletions pandas/plotting/_matplotlib/boxplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,8 @@ def _validate_color_args(self):
for key, values in self.color.items():
if key not in valid_keys:
raise ValueError(
"color dict contains invalid "
"key '{0}' "
"The key must be either {1}".format(key, valid_keys)
f"color dict contains invalid key '{key}'. "
f"The key must be either {valid_keys}"
)
else:
self.color = None
Expand Down Expand Up @@ -217,7 +216,7 @@ def _grouped_plot_by_column(
result = axes

byline = by[0] if len(by) == 1 else by
fig.suptitle("Boxplot grouped by {byline}".format(byline=byline))
fig.suptitle(f"Boxplot grouped by {byline}")
fig.subplots_adjust(bottom=0.15, top=0.9, left=0.1, right=0.9, wspace=0.2)

return result
Expand Down Expand Up @@ -268,9 +267,8 @@ def _get_colors():
result[key_to_index[key]] = value
else:
raise ValueError(
"color dict contains invalid "
"key '{0}' "
"The key must be either {1}".format(key, valid_keys)
f"color dict contains invalid key '{key}'. "
f"The key must be either {valid_keys}"
)
else:
result.fill(colors)
Expand Down
25 changes: 11 additions & 14 deletions pandas/plotting/_matplotlib/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ def time2num(d):
if isinstance(d, str):
parsed = tools.to_datetime(d)
if not isinstance(parsed, datetime):
raise ValueError("Could not parse time {d}".format(d=d))
raise ValueError(f"Could not parse time {d}")
return _to_ordinalf(parsed.time())
if isinstance(d, pydt.time):
return _to_ordinalf(d)
Expand Down Expand Up @@ -244,7 +244,7 @@ def get_datevalue(date, freq):
return date
elif date is None:
return None
raise ValueError("Unrecognizable date '{date}'".format(date=date))
raise ValueError(f"Unrecognizable date '{date}'")


def _dt_to_float_ordinal(dt):
Expand Down Expand Up @@ -421,12 +421,10 @@ def __call__(self):

if estimate > self.MAXTICKS * 2:
raise RuntimeError(
(
"MillisecondLocator estimated to generate "
"{estimate:d} ticks from {dmin} to {dmax}: "
"exceeds Locator.MAXTICKS"
"* 2 ({arg:d}) "
).format(estimate=estimate, dmin=dmin, dmax=dmax, arg=self.MAXTICKS * 2)
"MillisecondLocator estimated to generate "
f"{estimate:d} ticks from {dmin} to {dmax}: "
"exceeds Locator.MAXTICKS"
f"* 2 ({self.MAXTICKS * 2:d}) "
)

interval = self._get_interval()
Expand Down Expand Up @@ -582,7 +580,7 @@ def _daily_finder(vmin, vmax, freq):
elif freq == FreqGroup.FR_HR:
periodsperday = 24
else: # pragma: no cover
raise ValueError("unexpected frequency: {freq}".format(freq=freq))
raise ValueError(f"unexpected frequency: {freq}")
periodsperyear = 365 * periodsperday
periodspermonth = 28 * periodsperday

Expand Down Expand Up @@ -941,8 +939,7 @@ def get_finder(freq):
elif (freq >= FreqGroup.FR_BUS) or fgroup == FreqGroup.FR_WK:
return _daily_finder
else: # pragma: no cover
errmsg = "Unsupported frequency: {freq}".format(freq=freq)
raise NotImplementedError(errmsg)
raise NotImplementedError(f"Unsupported frequency: {freq}")


class TimeSeries_DateLocator(Locator):
Expand Down Expand Up @@ -1119,11 +1116,11 @@ def format_timedelta_ticks(x, pos, n_decimals):
h, m = divmod(m, 60)
d, h = divmod(h, 24)
decimals = int(ns * 10 ** (n_decimals - 9))
s = r"{:02d}:{:02d}:{:02d}".format(int(h), int(m), int(s))
s = f"{int(h):02d}:{int(m):02d}:{int(s):02d}"
if n_decimals > 0:
s += ".{{:0{:0d}d}}".format(n_decimals).format(decimals)
s += f".{decimals:0{n_decimals}d}"
if d != 0:
s = "{:d} days ".format(int(d)) + s
s = f"{int(d):d} days {s}"
return s

def __call__(self, x, pos=0):
Expand Down
23 changes: 10 additions & 13 deletions pandas/plotting/_matplotlib/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -349,8 +349,7 @@ def _setup_subplots(self):
if input_log - valid_log:
invalid_log = next(iter((input_log - valid_log)))
raise ValueError(
"Boolean, None and 'sym' are valid options,"
" '{}' is given.".format(invalid_log)
f"Boolean, None and 'sym' are valid options, '{invalid_log}' is given."
)

if self.logx is True or self.loglog is True:
Expand Down Expand Up @@ -501,14 +500,13 @@ def _adorn_subplots(self):
if self.subplots:
if is_list_like(self.title):
if len(self.title) != self.nseries:
msg = (
raise ValueError(
"The length of `title` must equal the number "
"of columns if using `title` of type `list` "
"and `subplots=True`.\n"
"length of title = {}\n"
"number of columns = {}"
).format(len(self.title), self.nseries)
raise ValueError(msg)
f"length of title = {len(self.title)}\n"
f"number of columns = {self.nseries}"
)

for (ax, title) in zip(self.axes, self.title):
ax.set_title(title)
Expand Down Expand Up @@ -813,11 +811,10 @@ def match_labels(data, e):
or (err_shape[1] != 2)
or (err_shape[2] != len(self.data))
):
msg = (
raise ValueError(
"Asymmetrical error bars should be provided "
+ "with the shape (%u, 2, %u)" % (self.nseries, len(self.data))
f"with the shape ({self.nseries}, 2, {len(self.data)})"
)
raise ValueError(msg)

# broadcast errors to each data series
if len(err) == 1:
Expand All @@ -827,7 +824,7 @@ def match_labels(data, e):
err = np.tile([err], (self.nseries, len(self.data)))

else:
msg = "No valid {label} detected".format(label=label)
msg = f"No valid {label} detected"
raise ValueError(msg)

return err
Expand Down Expand Up @@ -1178,7 +1175,7 @@ def _get_stacked_values(cls, ax, stacking_id, values, label):
raise ValueError(
"When stacked is True, each column must be either "
"all positive or negative."
"{0} contains both positive and negative values".format(label)
f"{label} contains both positive and negative values"
)

@classmethod
Expand Down Expand Up @@ -1473,7 +1470,7 @@ class PiePlot(MPLPlot):
def __init__(self, data, kind=None, **kwargs):
data = data.fillna(value=0)
if (data < 0).any().any():
raise ValueError("{0} doesn't allow negative values".format(kind))
raise ValueError(f"{kind} doesn't allow negative values")
MPLPlot.__init__(self, data, kind=kind, **kwargs)

def _args_adjust(self):
Expand Down
2 changes: 1 addition & 1 deletion pandas/plotting/_matplotlib/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -395,7 +395,7 @@ def lag_plot(series, lag=1, ax=None, **kwds):
if ax is None:
ax = plt.gca()
ax.set_xlabel("y(t)")
ax.set_ylabel("y(t + {lag})".format(lag=lag))
ax.set_ylabel(f"y(t + {lag})")
ax.scatter(y1, y2, **kwds)
return ax

Expand Down
2 changes: 1 addition & 1 deletion pandas/plotting/_matplotlib/style.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def _get_standard_colors(
cmap = colormap
colormap = cm.get_cmap(colormap)
if colormap is None:
raise ValueError("Colormap {0} is not recognized".format(cmap))
raise ValueError(f"Colormap {cmap} is not recognized")
colors = [colormap(num) for num in np.linspace(0, 1, num=num_colors)]
elif color is not None:
if colormap is not None:
Expand Down
3 changes: 2 additions & 1 deletion pandas/plotting/_matplotlib/timeseries.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,7 +307,8 @@ def _maybe_convert_index(ax, data):


def _format_coord(freq, t, y):
return "t = {0} y = {1:8f}".format(Period(ordinal=int(t), freq=freq), y)
time_period = Period(ordinal=int(t), freq=freq)
return f"t = {time_period} y = {y:8f}"


def format_dateaxis(subplot, freq, index):
Expand Down
9 changes: 3 additions & 6 deletions pandas/plotting/_matplotlib/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,10 +60,7 @@ def _get_layout(nplots, layout=None, layout_type="box"):

if nrows * ncols < nplots:
raise ValueError(
"Layout of {nrows}x{ncols} must be larger "
"than required size {nplots}".format(
nrows=nrows, ncols=ncols, nplots=nplots
)
f"Layout of {nrows}x{ncols} must be larger than required size {nplots}"
)

return layout
Expand Down Expand Up @@ -203,8 +200,8 @@ def _subplots(
return fig, ax
else:
raise ValueError(
"The number of passed axes must be {0}, the "
"same as the output plot".format(naxes)
f"The number of passed axes must be {naxes}, the "
"same as the output plot"
)

fig = ax.get_figure()
Expand Down
6 changes: 2 additions & 4 deletions pandas/plotting/_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -474,9 +474,7 @@ def __init__(self, deprecated=False):
def __getitem__(self, key):
key = self._get_canonical_key(key)
if key not in self:
raise ValueError(
"{key} is not a valid pandas plotting option".format(key=key)
)
raise ValueError(f"{key} is not a valid pandas plotting option")
return super().__getitem__(key)

def __setitem__(self, key, value):
Expand All @@ -486,7 +484,7 @@ def __setitem__(self, key, value):
def __delitem__(self, key):
key = self._get_canonical_key(key)
if key in self._DEFAULT_KEYS:
raise ValueError("Cannot remove default parameter {key}".format(key=key))
raise ValueError(f"Cannot remove default parameter {key}")
return super().__delitem__(key)

def __contains__(self, key):
Expand Down