Skip to content

Commit 1d94fc7

Browse files
ohad83proost
authored andcommitted
CLN - Change string formatting in plotting (pandas-dev#29781)
1 parent cabaf80 commit 1d94fc7

File tree

9 files changed

+52
-69
lines changed

9 files changed

+52
-69
lines changed

pandas/plotting/_core.py

+17-22
Original file line numberDiff line numberDiff line change
@@ -736,26 +736,23 @@ def _get_call_args(backend_name, data, args, kwargs):
736736
]
737737
else:
738738
raise TypeError(
739-
(
740-
"Called plot accessor for type {}, expected Series or DataFrame"
741-
).format(type(data).__name__)
739+
f"Called plot accessor for type {type(data).__name__}, "
740+
"expected Series or DataFrame"
742741
)
743742

744743
if args and isinstance(data, ABCSeries):
744+
positional_args = str(args)[1:-1]
745+
keyword_args = ", ".join(
746+
f"{name}={value!r}" for (name, default), value in zip(arg_def, args)
747+
)
745748
msg = (
746749
"`Series.plot()` should not be called with positional "
747750
"arguments, only keyword arguments. The order of "
748751
"positional arguments will change in the future. "
749-
"Use `Series.plot({})` instead of `Series.plot({})`."
750-
)
751-
positional_args = str(args)[1:-1]
752-
keyword_args = ", ".join(
753-
"{}={!r}".format(name, value)
754-
for (name, default), value in zip(arg_def, args)
755-
)
756-
warnings.warn(
757-
msg.format(keyword_args, positional_args), FutureWarning, stacklevel=3
752+
f"Use `Series.plot({keyword_args})` instead of "
753+
f"`Series.plot({positional_args})`."
758754
)
755+
warnings.warn(msg, FutureWarning, stacklevel=3)
759756

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

784781
if kind not in self._all_kinds:
785-
raise ValueError("{} is not a valid plot kind".format(kind))
782+
raise ValueError(f"{kind} is not a valid plot kind")
786783

787784
# The original data structured can be transformed before passed to the
788785
# backend. For example, for DataFrame is common to set the index as the
@@ -796,14 +793,13 @@ def __call__(self, *args, **kwargs):
796793
if isinstance(data, ABCDataFrame):
797794
return plot_backend.plot(data, x=x, y=y, kind=kind, **kwargs)
798795
else:
799-
raise ValueError(
800-
("plot kind {} can only be used for data frames").format(kind)
801-
)
796+
raise ValueError(f"plot kind {kind} can only be used for data frames")
802797
elif kind in self._series_kinds:
803798
if isinstance(data, ABCDataFrame):
804799
if y is None and kwargs.get("subplots") is False:
805-
msg = "{} requires either y column or 'subplots=True'"
806-
raise ValueError(msg.format(kind))
800+
raise ValueError(
801+
f"{kind} requires either y column or 'subplots=True'"
802+
)
807803
elif y is not None:
808804
if is_integer(y) and not data.columns.holds_integer():
809805
y = data.columns[y]
@@ -1639,12 +1635,11 @@ def _find_backend(backend: str):
16391635
_backends[backend] = module
16401636
return module
16411637

1642-
msg = (
1643-
"Could not find plotting backend '{name}'. Ensure that you've installed the "
1644-
"package providing the '{name}' entrypoint, or that the package has a"
1638+
raise ValueError(
1639+
f"Could not find plotting backend '{backend}'. Ensure that you've installed "
1640+
f"the package providing the '{backend}' entrypoint, or that the package has a "
16451641
"top-level `.plot` method."
16461642
)
1647-
raise ValueError(msg.format(name=backend))
16481643

16491644

16501645
def _get_plot_backend(backend=None):

pandas/plotting/_matplotlib/boxplot.py

+5-7
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,8 @@ def _validate_color_args(self):
7474
for key, values in self.color.items():
7575
if key not in valid_keys:
7676
raise ValueError(
77-
"color dict contains invalid "
78-
"key '{0}' "
79-
"The key must be either {1}".format(key, valid_keys)
77+
f"color dict contains invalid key '{key}'. "
78+
f"The key must be either {valid_keys}"
8079
)
8180
else:
8281
self.color = None
@@ -217,7 +216,7 @@ def _grouped_plot_by_column(
217216
result = axes
218217

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

223222
return result
@@ -268,9 +267,8 @@ def _get_colors():
268267
result[key_to_index[key]] = value
269268
else:
270269
raise ValueError(
271-
"color dict contains invalid "
272-
"key '{0}' "
273-
"The key must be either {1}".format(key, valid_keys)
270+
f"color dict contains invalid key '{key}'. "
271+
f"The key must be either {valid_keys}"
274272
)
275273
else:
276274
result.fill(colors)

pandas/plotting/_matplotlib/converter.py

+11-14
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ def time2num(d):
125125
if isinstance(d, str):
126126
parsed = tools.to_datetime(d)
127127
if not isinstance(parsed, datetime):
128-
raise ValueError("Could not parse time {d}".format(d=d))
128+
raise ValueError(f"Could not parse time {d}")
129129
return _to_ordinalf(parsed.time())
130130
if isinstance(d, pydt.time):
131131
return _to_ordinalf(d)
@@ -244,7 +244,7 @@ def get_datevalue(date, freq):
244244
return date
245245
elif date is None:
246246
return None
247-
raise ValueError("Unrecognizable date '{date}'".format(date=date))
247+
raise ValueError(f"Unrecognizable date '{date}'")
248248

249249

250250
def _dt_to_float_ordinal(dt):
@@ -421,12 +421,10 @@ def __call__(self):
421421

422422
if estimate > self.MAXTICKS * 2:
423423
raise RuntimeError(
424-
(
425-
"MillisecondLocator estimated to generate "
426-
"{estimate:d} ticks from {dmin} to {dmax}: "
427-
"exceeds Locator.MAXTICKS"
428-
"* 2 ({arg:d}) "
429-
).format(estimate=estimate, dmin=dmin, dmax=dmax, arg=self.MAXTICKS * 2)
424+
"MillisecondLocator estimated to generate "
425+
f"{estimate:d} ticks from {dmin} to {dmax}: "
426+
"exceeds Locator.MAXTICKS"
427+
f"* 2 ({self.MAXTICKS * 2:d}) "
430428
)
431429

432430
interval = self._get_interval()
@@ -582,7 +580,7 @@ def _daily_finder(vmin, vmax, freq):
582580
elif freq == FreqGroup.FR_HR:
583581
periodsperday = 24
584582
else: # pragma: no cover
585-
raise ValueError("unexpected frequency: {freq}".format(freq=freq))
583+
raise ValueError(f"unexpected frequency: {freq}")
586584
periodsperyear = 365 * periodsperday
587585
periodspermonth = 28 * periodsperday
588586

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

947944

948945
class TimeSeries_DateLocator(Locator):
@@ -1119,11 +1116,11 @@ def format_timedelta_ticks(x, pos, n_decimals):
11191116
h, m = divmod(m, 60)
11201117
d, h = divmod(h, 24)
11211118
decimals = int(ns * 10 ** (n_decimals - 9))
1122-
s = r"{:02d}:{:02d}:{:02d}".format(int(h), int(m), int(s))
1119+
s = f"{int(h):02d}:{int(m):02d}:{int(s):02d}"
11231120
if n_decimals > 0:
1124-
s += ".{{:0{:0d}d}}".format(n_decimals).format(decimals)
1121+
s += f".{decimals:0{n_decimals}d}"
11251122
if d != 0:
1126-
s = "{:d} days ".format(int(d)) + s
1123+
s = f"{int(d):d} days {s}"
11271124
return s
11281125

11291126
def __call__(self, x, pos=0):

pandas/plotting/_matplotlib/core.py

+10-13
Original file line numberDiff line numberDiff line change
@@ -349,8 +349,7 @@ def _setup_subplots(self):
349349
if input_log - valid_log:
350350
invalid_log = next(iter((input_log - valid_log)))
351351
raise ValueError(
352-
"Boolean, None and 'sym' are valid options,"
353-
" '{}' is given.".format(invalid_log)
352+
f"Boolean, None and 'sym' are valid options, '{invalid_log}' is given."
354353
)
355354

356355
if self.logx is True or self.loglog is True:
@@ -501,14 +500,13 @@ def _adorn_subplots(self):
501500
if self.subplots:
502501
if is_list_like(self.title):
503502
if len(self.title) != self.nseries:
504-
msg = (
503+
raise ValueError(
505504
"The length of `title` must equal the number "
506505
"of columns if using `title` of type `list` "
507506
"and `subplots=True`.\n"
508-
"length of title = {}\n"
509-
"number of columns = {}"
510-
).format(len(self.title), self.nseries)
511-
raise ValueError(msg)
507+
f"length of title = {len(self.title)}\n"
508+
f"number of columns = {self.nseries}"
509+
)
512510

513511
for (ax, title) in zip(self.axes, self.title):
514512
ax.set_title(title)
@@ -813,11 +811,10 @@ def match_labels(data, e):
813811
or (err_shape[1] != 2)
814812
or (err_shape[2] != len(self.data))
815813
):
816-
msg = (
814+
raise ValueError(
817815
"Asymmetrical error bars should be provided "
818-
+ "with the shape (%u, 2, %u)" % (self.nseries, len(self.data))
816+
f"with the shape ({self.nseries}, 2, {len(self.data)})"
819817
)
820-
raise ValueError(msg)
821818

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

829826
else:
830-
msg = "No valid {label} detected".format(label=label)
827+
msg = f"No valid {label} detected"
831828
raise ValueError(msg)
832829

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

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

14791476
def _args_adjust(self):

pandas/plotting/_matplotlib/misc.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -395,7 +395,7 @@ def lag_plot(series, lag=1, ax=None, **kwds):
395395
if ax is None:
396396
ax = plt.gca()
397397
ax.set_xlabel("y(t)")
398-
ax.set_ylabel("y(t + {lag})".format(lag=lag))
398+
ax.set_ylabel(f"y(t + {lag})")
399399
ax.scatter(y1, y2, **kwds)
400400
return ax
401401

pandas/plotting/_matplotlib/style.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def _get_standard_colors(
2020
cmap = colormap
2121
colormap = cm.get_cmap(colormap)
2222
if colormap is None:
23-
raise ValueError("Colormap {0} is not recognized".format(cmap))
23+
raise ValueError(f"Colormap {cmap} is not recognized")
2424
colors = [colormap(num) for num in np.linspace(0, 1, num=num_colors)]
2525
elif color is not None:
2626
if colormap is not None:

pandas/plotting/_matplotlib/timeseries.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -307,7 +307,8 @@ def _maybe_convert_index(ax, data):
307307

308308

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

312313

313314
def format_dateaxis(subplot, freq, index):

pandas/plotting/_matplotlib/tools.py

+3-6
Original file line numberDiff line numberDiff line change
@@ -60,10 +60,7 @@ def _get_layout(nplots, layout=None, layout_type="box"):
6060

6161
if nrows * ncols < nplots:
6262
raise ValueError(
63-
"Layout of {nrows}x{ncols} must be larger "
64-
"than required size {nplots}".format(
65-
nrows=nrows, ncols=ncols, nplots=nplots
66-
)
63+
f"Layout of {nrows}x{ncols} must be larger than required size {nplots}"
6764
)
6865

6966
return layout
@@ -203,8 +200,8 @@ def _subplots(
203200
return fig, ax
204201
else:
205202
raise ValueError(
206-
"The number of passed axes must be {0}, the "
207-
"same as the output plot".format(naxes)
203+
f"The number of passed axes must be {naxes}, the "
204+
"same as the output plot"
208205
)
209206

210207
fig = ax.get_figure()

pandas/plotting/_misc.py

+2-4
Original file line numberDiff line numberDiff line change
@@ -446,9 +446,7 @@ def __init__(self, deprecated=False):
446446
def __getitem__(self, key):
447447
key = self._get_canonical_key(key)
448448
if key not in self:
449-
raise ValueError(
450-
"{key} is not a valid pandas plotting option".format(key=key)
451-
)
449+
raise ValueError(f"{key} is not a valid pandas plotting option")
452450
return super().__getitem__(key)
453451

454452
def __setitem__(self, key, value):
@@ -458,7 +456,7 @@ def __setitem__(self, key, value):
458456
def __delitem__(self, key):
459457
key = self._get_canonical_key(key)
460458
if key in self._DEFAULT_KEYS:
461-
raise ValueError("Cannot remove default parameter {key}".format(key=key))
459+
raise ValueError(f"Cannot remove default parameter {key}")
462460
return super().__delitem__(key)
463461

464462
def __contains__(self, key):

0 commit comments

Comments
 (0)