Skip to content

Commit 266c20e

Browse files
authored
Merge pull request #376 from nschloe/new-format
specify format as .8e, not {:.8e}
2 parents 2a5059d + f7f1044 commit 266c20e

File tree

14 files changed

+124
-167
lines changed

14 files changed

+124
-167
lines changed

test/helpers.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ def _unidiff_output(expected, actual):
3333
def assert_equality(plot, filename, **extra_get_tikz_code_args):
3434
plot()
3535
code = tikzplotlib.get_tikz_code(
36-
include_disclaimer=False, float_format="{:.8g}", **extra_get_tikz_code_args
36+
include_disclaimer=False, float_format=".8g", **extra_get_tikz_code_args
3737
)
3838
plt.close()
3939

test/refresh_reference_files.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ def _main():
2424
spec.loader.exec_module(module)
2525
module.plot()
2626

27-
code = tpl.get_tikz_code(include_disclaimer=False, float_format="{:.8g}")
27+
code = tpl.get_tikz_code(include_disclaimer=False, float_format=".8g")
2828
plt.close()
2929

3030
tex_filename = filename[:-3] + "_reference.tex"

tikzplotlib/_axes.py

Lines changed: 23 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -53,26 +53,24 @@ def __init__(self, data, obj): # noqa: C901
5353
xlabel = _common_texification(xlabel)
5454
self.axis_options.append(f"xlabel={{{xlabel}}}")
5555
if xrotation != 0:
56-
self.axis_options.append(
57-
"xlabel style={{rotate={}}}".format(xrotation - 90)
58-
)
56+
self.axis_options.append("xlabel style={{rotate={xrotation - 90)}}}")
5957
ylabel = obj.get_ylabel()
6058
yrotation = obj.yaxis.get_label().get_rotation()
6159
if ylabel:
6260
ylabel = _common_texification(ylabel)
6361
self.axis_options.append(f"ylabel={{{ylabel}}}")
6462
if yrotation != 90:
65-
self.axis_options.append(
66-
"ylabel style={{rotate={}}}".format(yrotation - 90)
67-
)
63+
self.axis_options.append("ylabel style={{rotate={yrotation - 90}}}")
6864

6965
# Axes limits.
7066
ff = data["float format"]
7167
xlim = list(obj.get_xlim())
68+
xlim0, xlim1 = sorted(xlim)
7269
ylim = list(obj.get_ylim())
70+
ylim0, ylim1 = sorted(ylim)
7371
# Sort the limits so make sure that the smaller of the two is actually *min.
74-
self.axis_options.append(("xmin=" + ff + ", xmax=" + ff).format(*sorted(xlim)))
75-
self.axis_options.append(("ymin=" + ff + ", ymax=" + ff).format(*sorted(ylim)))
72+
self.axis_options.append(f"xmin={xlim0:{ff}}, xmax={xlim1:{ff}}")
73+
self.axis_options.append(f"ymin={ylim0:{ff}}, ymax={ylim1:{ff}}")
7674
# When the axis is inverted add additional option
7775
if xlim != sorted(xlim):
7876
self.axis_options.append("x dir=reverse")
@@ -395,8 +393,8 @@ def _colorbar(self, colorbar, data):
395393
self.axis_options.append("colormap/" + mycolormap)
396394

397395
ff = data["float format"]
398-
self.axis_options.append(("point meta min=" + ff).format(limits[0]))
399-
self.axis_options.append(("point meta max=" + ff).format(limits[1]))
396+
self.axis_options.append(f"point meta min={limits[0]:{ff}}")
397+
self.axis_options.append(f"point meta max={limits[1]:{ff}}")
400398

401399
if colorbar_styles:
402400
self.axis_options.append(
@@ -417,7 +415,7 @@ def _subplot(self, obj, data):
417415
# subplotspec geometry positioning is 0-based
418416
self.subplot_index = geom[2] + 1
419417
if "is_in_groupplot_env" not in data or not data["is_in_groupplot_env"]:
420-
group_style = ["group size={} by {}".format(geom[1], geom[0])]
418+
group_style = [f"group size={geom[1]} by {geom[0]}"]
421419
group_style.extend(data["extra groupstyle options [base]"])
422420
options = ["group style={{{}}}".format(", ".join(group_style))]
423421
self.content.append(
@@ -460,12 +458,12 @@ def _get_label_rotation_and_horizontal_alignment(self, obj, data, x_or_y):
460458
values = []
461459

462460
if any(tick_labels_rotation) != 0:
463-
values.append("rotate={}".format(tick_labels_rotation[0]))
461+
values.append(f"rotate={tick_labels_rotation[0]}")
464462

465463
# Horizontal alignment will be ignored if no 'x/y tick label text width' has
466464
# been passed in the 'extra' parameter
467465
if tick_label_text_width:
468-
values.append("align={}".format(tick_labels_horizontal_alignment[0]))
466+
values.append(f"align={tick_labels_horizontal_alignment[0]}")
469467
values.append(f"text width={tick_label_text_width}")
470468

471469
if values:
@@ -476,7 +474,7 @@ def _get_label_rotation_and_horizontal_alignment(self, obj, data, x_or_y):
476474
values = []
477475

478476
if tick_labels_rotation_same_value:
479-
values.append("rotate={}".format(tick_labels_rotation[0]))
477+
values.append("rotate={tick_labels_rotation[0]}")
480478
else:
481479
values.append(
482480
"rotate={{{},0}}[\\ticknum]".format(
@@ -488,20 +486,14 @@ def _get_label_rotation_and_horizontal_alignment(self, obj, data, x_or_y):
488486
# passed in the 'extra' parameter
489487
if tick_label_text_width:
490488
if tick_labels_horizontal_alignment_same_value:
491-
values.append(
492-
"align={}".format(tick_labels_horizontal_alignment[0])
493-
)
489+
values.append(f"align={tick_labels_horizontal_alignment[0]}")
494490
values.append(f"text width={tick_label_text_width}")
495491
else:
496492
for idx, x in enumerate(tick_labels_horizontal_alignment):
497-
label_style += "{}_tick_label_ha_{}/.initial = {}".format(
498-
x_or_y, idx, x
499-
)
493+
label_style += f"{x_or_y}_tick_label_ha_{idx}/.initial = {x}"
500494

501495
values.append(
502-
"align=\\pgfkeysvalueof{{/pgfplots/{}_tick_label_ha_\\ticknum}}".format(
503-
x_or_y
504-
)
496+
f"align=\\pgfkeysvalueof{{/pgfplots/{x_or_y}_tick_label_ha_\\ticknum}}"
505497
)
506498
values.append(f"text width={tick_label_text_width}")
507499

@@ -587,7 +579,7 @@ def _get_ticks(data, xy, ticks, ticklabels):
587579
ff = data["float format"]
588580
axis_options.append(
589581
"{}tick={{{}}}".format(
590-
xy, ",".join([ff.format(el) for el in pgfplots_ticks])
582+
xy, ",".join([f"{el:{ff}}" for el in pgfplots_ticks])
591583
)
592584
)
593585
else:
@@ -726,11 +718,10 @@ def _handle_linear_segmented_color_map(cmap, data):
726718

727719
color_changes = []
728720
ff = data["float format"]
729-
for (k, x) in enumerate(X):
721+
for k, x in enumerate(X):
730722
color_changes.append(
731-
("rgb({}{})=(" + ff + "," + ff + "," + ff + ")").format(
732-
*((x, unit) + colors[k])
733-
)
723+
f"rgb({x}{unit})="
724+
f"({colors[k][0]:{ff}},{colors[k][1]:{ff}},{colors[k][2]:{ff}})"
734725
)
735726

736727
colormap_string = "{{mymap}}{{[1{}]\n {}\n}}".format(
@@ -769,19 +760,15 @@ def _handle_listed_color_map(cmap, data):
769760
ff = data["float format"]
770761
if cmap.N is None or cmap.N == len(cmap.colors):
771762
colors = [
772-
("rgb({}{})=(" + ff + "," + ff + "," + ff + ")").format(
773-
k, unit, rgb[0], rgb[1], rgb[2]
774-
)
775-
for (k, rgb) in enumerate(cmap.colors)
763+
f"rgb({k}{unit})=({rgb[0]:{ff}},{rgb[1]:{ff}},{rgb[2]:{ff}})"
764+
for k, rgb in enumerate(cmap.colors)
776765
]
777766
else:
778767
reps = int(float(cmap.N) / len(cmap.colors) - 0.5) + 1
779768
repeated_cols = reps * cmap.colors
780769
colors = [
781-
("rgb({}{})=(" + ff + "," + ff + "," + ff + ")").format(
782-
k, unit, rgb[0], rgb[1], rgb[2]
783-
)
784-
for (k, rgb) in enumerate(repeated_cols[: cmap.N])
770+
"rgb({k}{unit})=({rgb[0]:{ff}},{rgb[1]:{ff}},{rgb[2]:{ff}})"
771+
for k, rgb in enumerate(repeated_cols[: cmap.N])
785772
]
786773
colormap_string = "{{mymap}}{{[1{}]\n {}\n}}".format(unit, ";\n ".join(colors))
787774
is_custom_colormap = True

tikzplotlib/_color.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ def mpl_color2xcolor(data, matplotlib_color):
6868
# already accounted for by checking in available_colors above.
6969
if all(my_col[:3] == alpha * rgb) and 0.0 < alpha < 1.0:
7070
ff = data["float format"]
71-
xcol = name + (f"!{ff}!black".format(alpha * 100))
71+
xcol = name + f"!{alpha*100:{ff}}!black"
7272
return data, xcol, my_col
7373

7474
# Lookup failed, add it to the custom list.

tikzplotlib/_files.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44

55
def _gen_filename(data, nb_key, ext):
6-
name = data["base name"] + "-{:03d}{}".format(data[nb_key], ext)
6+
name = data["base name"] + f"-{data[nb_key]:03d}{ext}"
77
return os.path.join(data["output dir"], name), name
88

99

tikzplotlib/_hatches.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ def _mpl_hatch2pgfp_pattern(data, hatch, color_name, color_rgba):
106106
ff = data["float format"]
107107
# PGFPlots render patterns according to opacity fill.
108108
# This change is within the scope of the postaction
109-
pattern_options.append(("fill opacity=" + ff).format(color_rgba[3]))
109+
pattern_options.append(f"fill opacity={color_rgba[3]:{ff}}")
110110

111111
# Add pattern as postaction to allow color fill and pattern together
112112
# https://tex.stackexchange.com/questions/24964/

tikzplotlib/_image.py

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,8 @@ def draw_image(data, obj):
5252
# \includegraphics fails unexpectedly in some cases
5353
ff = data["float format"]
5454
content.append(
55-
(
56-
"\\addplot graphics [includegraphics cmd=\\pgfimage,"
57-
"xmin=" + ff + ", xmax=" + ff + ", "
58-
"ymin=" + ff + ", ymax=" + ff + "] {{{}}};\n"
59-
).format(*(extent + (rel_filepath,)))
55+
"\\addplot graphics [includegraphics cmd=\\pgfimage,"
56+
f"xmin={extent[0]:{ff}}, xmax={extent[1]:{ff}}, "
57+
f"ymin={extent[2]:{ff}}, ymax={extent[3]:{ff}}] {{{rel_filepath}}};\n"
6058
)
61-
6259
return data, content

tikzplotlib/_legend.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -45,9 +45,7 @@ def draw_legend(data, obj):
4545
]
4646
if position:
4747
ff = data["float format"]
48-
legend_style.append(
49-
("at={{(" + ff + "," + ff + ")}}").format(position[0], position[1])
50-
)
48+
legend_style.append(f"at={{({position[0]:{ff}},{position[1]:{ff}})}}")
5149
if anchor:
5250
legend_style.append(f"anchor={anchor}")
5351

tikzplotlib/_line2d.py

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -143,7 +143,7 @@ def _marker(
143143
ff = data["float format"]
144144
# setting half size because pgfplots counts the radius/half-width
145145
pgf_size = 0.5 * mark_size
146-
addplot_options.append(f"mark size={pgf_size:{ff[2:-1]}}")
146+
addplot_options.append(f"mark size={pgf_size:{ff}}")
147147

148148
mark_every = obj.get_markevery()
149149
if mark_every:
@@ -200,7 +200,7 @@ def _table(obj, data): # noqa: C901
200200
xdata = xdata_alt
201201
elif isinstance(xdata_alt[0], str):
202202
data["current axes"].axis_options += [
203-
"xtick={{{}}}".format(",".join([ff.format(x) for x in xdata])),
203+
"xtick={{{}}}".format(",".join([f"{x:{ff}}" for x in xdata])),
204204
"xticklabels={{{}}}".format(",".join(xdata_alt)),
205205
]
206206
xdata, ydata = transform_to_data_coordinates(obj, xdata, ydata)
@@ -237,7 +237,7 @@ def _table(obj, data): # noqa: C901
237237

238238
if isinstance(xdata[0], datetime.datetime):
239239
xdata = [date.strftime("%Y-%m-%d %H:%M") for date in xdata]
240-
xformat = "{}"
240+
xformat = ""
241241
col_sep = ","
242242
opts = ["header=false", "col sep=comma"]
243243
data["current axes"].axis_options.append("date coordinates in=x")
@@ -269,26 +269,16 @@ def _table(obj, data): # noqa: C901
269269
content.append("table {%\n")
270270

271271
plot_table = []
272+
table_row_sep = data["table_row_sep"]
273+
ydata[ydata_mask] = numpy.nan
272274
if any(ydata_mask):
273275
# matplotlib jumps at masked images, while PGFPlots by default interpolates.
274276
# Hence, if we have a masked plot, make sure that PGFPlots jumps as well.
275277
if "unbounded coords=jump" not in data["current axes"].axis_options:
276278
data["current axes"].axis_options.append("unbounded coords=jump")
277279

278-
for (x, y, is_masked) in zip(xdata, ydata, ydata_mask):
279-
if is_masked:
280-
plot_table.append(
281-
(xformat + col_sep + "nan" + data["table_row_sep"]).format(x)
282-
)
283-
else:
284-
plot_table.append(
285-
(xformat + col_sep + ff + data["table_row_sep"]).format(x, y)
286-
)
287-
else:
288-
for x, y in zip(xdata, ydata):
289-
plot_table.append(
290-
(xformat + col_sep + ff + data["table_row_sep"]).format(x, y)
291-
)
280+
for x, y in zip(xdata, ydata):
281+
plot_table.append(f"{x:{xformat}}{col_sep}{y:{ff}}{table_row_sep}")
292282

293283
if data["externalize tables"]:
294284
filename, rel_filepath = _files.new_filename(data, "table", ".tsv")

tikzplotlib/_patch.py

Lines changed: 20 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -139,15 +139,12 @@ def _draw_rectangle(data, obj, draw_options):
139139
left_lower_x = obj.get_x()
140140
left_lower_y = obj.get_y()
141141
ff = data["float format"]
142+
do = ",".join(draw_options)
143+
right_upper_x = left_lower_x + obj.get_width()
144+
right_upper_y = left_lower_y + obj.get_height()
142145
cont = (
143-
"\\draw[{}] (axis cs:" + ff + "," + ff + ") "
144-
"rectangle (axis cs:" + ff + "," + ff + ");\n"
145-
).format(
146-
",".join(draw_options),
147-
left_lower_x,
148-
left_lower_y,
149-
left_lower_x + obj.get_width(),
150-
left_lower_y + obj.get_height(),
146+
f"\\draw[{do}] (axis cs:{left_lower_x:{ff}},{left_lower_y:{ff}}) "
147+
f"rectangle (axis cs:{right_upper_x:{ff}},{right_upper_y:{ff}});\n"
151148
)
152149

153150
if label != "_nolegend_" and label not in data["rectangle_legends"]:
@@ -169,21 +166,15 @@ def _draw_ellipse(data, obj, draw_options):
169166
ff = data["float format"]
170167

171168
if obj.angle != 0:
172-
fmt = "rotate around={{" + ff + ":(axis cs:" + ff + "," + ff + ")}}"
173-
draw_options.append(fmt.format(obj.angle, x, y))
169+
draw_options.append(
170+
f"rotate around={{{obj.angle:{ff}}:(axis cs:{x:{ff}},{y:{ff}})}}"
171+
)
174172

173+
do = ",".join(draw_options)
175174
content = (
176-
"\\draw[{}] (axis cs:"
177-
+ ff
178-
+ ","
179-
+ ff
180-
+ ") ellipse ("
181-
+ ff
182-
+ " and "
183-
+ ff
184-
+ ");\n"
185-
).format(",".join(draw_options), x, y, 0.5 * obj.width, 0.5 * obj.height)
186-
175+
f"\\draw[{do}] (axis cs:{x:{ff}},{y:{ff}}) ellipse "
176+
f"({0.5 * obj.width:{ff}} and {0.5 * obj.height:{ff}});\n"
177+
)
187178
content += _patch_legend(obj, draw_options, "area legend")
188179

189180
return data, content
@@ -194,11 +185,11 @@ def _draw_circle(data, obj, draw_options):
194185
"""
195186
x, y = obj.center
196187
ff = data["float format"]
188+
do = ",".join(draw_options)
197189
content = (
198-
"\\draw[{}] (axis cs:" + ff + "," + ff + ") circle (" + ff + ");\n"
199-
).format(",".join(draw_options), x, y, obj.get_radius())
190+
f"\\draw[{do}] (axis cs:{x:{ff}},{y:{ff}}) circle ({obj.get_radius():{ff}});\n"
191+
)
200192
content += _patch_legend(obj, draw_options, "area legend")
201-
202193
return data, content
203194

204195

@@ -207,9 +198,11 @@ def _draw_fancy_arrow(data, obj, draw_options):
207198
ff = data["float format"]
208199
if obj._posA_posB is not None:
209200
posA, posB = obj._posA_posB
210-
content = "\\draw[{{}}] (axis cs:{ff},{ff}) -- (axis cs:{ff},{ff});\n".format(
211-
ff=ff
212-
).format(",".join(style), *posA, *posB)
201+
do = ",".join(style)
202+
content = (
203+
f"\\draw[{do}] (axis cs:{posA[0]:{ff}},{posA[1]:{ff}}) -- "
204+
f"(axis cs:{posB[0]:{ff}},{posB[1]:{ff}});\n"
205+
)
213206
else:
214207
data, content, _, _ = mypath.draw_path(
215208
data, obj._path_original, draw_options=draw_options + style

0 commit comments

Comments
 (0)