diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index da1e06dccc65d..beb276478070e 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -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": @@ -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 @@ -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] @@ -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): diff --git a/pandas/plotting/_matplotlib/boxplot.py b/pandas/plotting/_matplotlib/boxplot.py index 274f06cd3ec1d..7bcca659ee3f6 100644 --- a/pandas/plotting/_matplotlib/boxplot.py +++ b/pandas/plotting/_matplotlib/boxplot.py @@ -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 @@ -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 @@ -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) diff --git a/pandas/plotting/_matplotlib/converter.py b/pandas/plotting/_matplotlib/converter.py index 4b0ba2bd423df..feb895a099da5 100644 --- a/pandas/plotting/_matplotlib/converter.py +++ b/pandas/plotting/_matplotlib/converter.py @@ -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) @@ -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): @@ -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() @@ -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 @@ -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): @@ -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): diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 5341dc3a6338a..20af25af7bc88 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -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: @@ -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) @@ -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: @@ -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 @@ -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 @@ -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): diff --git a/pandas/plotting/_matplotlib/misc.py b/pandas/plotting/_matplotlib/misc.py index 6d2363668e650..0720f544203f7 100644 --- a/pandas/plotting/_matplotlib/misc.py +++ b/pandas/plotting/_matplotlib/misc.py @@ -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 diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py index 927b9cf4e392a..fd69265b18a5b 100644 --- a/pandas/plotting/_matplotlib/style.py +++ b/pandas/plotting/_matplotlib/style.py @@ -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: diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index 931c699d9b9fd..fa9585e1fc229 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -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): diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index bcbe5eea8b5ab..dd4034a97f58e 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -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 @@ -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() diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 6c8bcdada5957..965da21488c8d 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -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): @@ -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):