Skip to content

Commit b31ed3f

Browse files
committed
FIX: correctly handle generic font families in svg text-as-text mode
This: - expands the generic fonts families to the user configured specific fonts in the svg output - ensures that each font family only appears once per text element in the svg output - ensures that generic families are unquoted and specific families are closes #22528 closes #23492
1 parent 276436a commit b31ed3f

File tree

1 file changed

+47
-2
lines changed

1 file changed

+47
-2
lines changed

lib/matplotlib/backends/backend_svg.py

Lines changed: 47 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1151,10 +1151,55 @@ def _draw_text_as_text(self, gc, x, y, s, prop, angle, ismath, mtext=None):
11511151
weight = fm.weight_dict[prop.get_weight()]
11521152
if weight != 400:
11531153
font_parts.append(f'{weight}')
1154+
1155+
# TODO lift this up and add caching
1156+
def _format_font_name(fn):
1157+
normalize_names = {
1158+
'sans': 'sans-serif',
1159+
'sans serif': 'sans-serif'
1160+
}
1161+
# A generic font family. We need to do two things:
1162+
# 1. list all of the configured fonts with quoted names
1163+
# 2. append the generic name unquoted
1164+
if fn in fm.font_family_aliases:
1165+
# fix spelling of sans-serif
1166+
# we accept 3 ways CSS only supports 1
1167+
fn = normalize_names.get(fn, fn)
1168+
# get all of the font names and fix spelling of sans-serif
1169+
# if it comes back
1170+
aliases = [
1171+
normalize_names.get(_, _) for _ in
1172+
fm.FontManager._expand_aliases(fn)
1173+
]
1174+
# make sure the generic name appears at least once
1175+
aliases.append(fn)
1176+
1177+
def unique_iter(inp):
1178+
"""Only return unique values."""
1179+
seen = set()
1180+
for i in inp:
1181+
if i not in seen:
1182+
seen.add(i)
1183+
yield i
1184+
1185+
return ', '.join(
1186+
[
1187+
# generic font families must not be quoted
1188+
a if a in fm.font_family_aliases
1189+
# specific font families must be quoted
1190+
else repr(a)
1191+
# make sure each font family only shows up once
1192+
for a in unique_iter(aliases)
1193+
]
1194+
)
1195+
# specific font families must be quoted
1196+
else:
1197+
return repr(fn)
1198+
11541199
font_parts.extend([
11551200
f'{_short_float_fmt(prop.get_size())}px',
1156-
# ensure quoting
1157-
f'{", ".join(repr(f) for f in prop.get_family())}',
1201+
# ensure quoting and expansion of font names
1202+
", ".join(_format_font_name(f) for f in prop.get_family()),
11581203
])
11591204
style['font'] = ' '.join(font_parts)
11601205
if prop.get_stretch() != 'normal':

0 commit comments

Comments
 (0)