本文整理汇总了Python中matplotlib.font_manager.findfont函数的典型用法代码示例。如果您正苦于以下问题:Python findfont函数的具体用法?Python findfont怎么用?Python findfont使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了findfont函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _get_font_afm
def _get_font_afm(self, prop):
key = hash(prop)
font = self.afmfontd.get(key)
if font is None:
fname = findfont(prop, fontext='afm')
font = self.afmfontd.get(fname)
if font is None:
font = AFM(file(findfont(prop, fontext='afm')))
self.afmfontd[fname] = font
self.afmfontd[key] = font
return font
示例2: __enter__
def __enter__(self):
"""
Set matplotlib defaults.
"""
MatplotlibBackend.switch_backend("AGG", sloppy=False)
from matplotlib import font_manager, rcParams, rcdefaults
import locale
try:
locale.setlocale(locale.LC_ALL, native_str('en_US.UTF-8'))
except Exception:
try:
locale.setlocale(locale.LC_ALL,
native_str('English_United States.1252'))
except Exception:
msg = "Could not set locale to English/United States. " + \
"Some date-related tests may fail"
warnings.warn(msg)
# set matplotlib builtin default settings for testing
rcdefaults()
if self.style is not None:
self.style.__enter__()
if MATPLOTLIB_VERSION >= [2, 0, 0]:
default_font = 'DejaVu Sans'
else:
default_font = 'Bitstream Vera Sans'
rcParams['font.family'] = default_font
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', 'findfont:.*')
font_manager.findfont(default_font)
if w:
warnings.warn('Unable to find the ' + default_font + ' font. '
'Plotting tests will likely fail.')
try:
rcParams['text.hinting'] = False
except KeyError:
warnings.warn("could not set rcParams['text.hinting']")
try:
rcParams['text.hinting_factor'] = 8
except KeyError:
warnings.warn("could not set rcParams['text.hinting_factor']")
if self.plt_close_all_enter:
import matplotlib.pyplot as plt
try:
plt.close("all")
except Exception:
pass
return self
示例3: test_font_priority
def test_font_priority():
with rc_context(rc={
'font.sans-serif':
['cmmi10', 'Bitstream Vera Sans']}):
font = findfont(
FontProperties(family=["sans-serif"]))
assert_equal(os.path.basename(font), 'cmmi10.ttf')
示例4: test_find_ttc
def test_find_ttc():
fp = FontProperties(family=["WenQuanYi Zen Hei"])
if Path(findfont(fp)).name != "wqy-zenhei.ttc":
# Travis appears to fail to pick up the ttc file sometimes. Try to
# rebuild the cache and try again.
fm._rebuild()
assert Path(findfont(fp)).name == "wqy-zenhei.ttc"
fig, ax = plt.subplots()
ax.text(.5, .5, "\N{KANGXI RADICAL DRAGON}", fontproperties=fp)
fig.savefig(BytesIO(), format="raw")
fig.savefig(BytesIO(), format="svg")
with pytest.raises(RuntimeError):
fig.savefig(BytesIO(), format="pdf")
with pytest.raises(RuntimeError):
fig.savefig(BytesIO(), format="ps")
示例5: _get_font
def _get_font(self, prop):
fname = findfont(prop)
font = get_font(fname)
font.clear()
size = prop.get_size_in_points()
font.set_size(size, 72.0)
return font
示例6: test_fontinfo
def test_fontinfo():
import matplotlib.font_manager as font_manager
import matplotlib.ft2font as ft2font
fontpath = font_manager.findfont("Bitstream Vera Sans")
font = ft2font.FT2Font(fontpath)
table = font.get_sfnt_table("head")
assert table['version'] == (1, 0)
示例7: _get_agg_font
def _get_agg_font(self, prop):
"""
Get the font for text instance t, cacheing for efficiency
"""
if __debug__: verbose.report('RendererAgg._get_agg_font',
'debug-annoying')
key = hash(prop)
font = RendererAgg._fontd.get(key)
if font is None:
fname = findfont(prop)
font = RendererAgg._fontd.get(fname)
if font is None:
font = FT2Font(
fname,
hinting_factor=rcParams['text.hinting_factor'])
RendererAgg._fontd[fname] = font
RendererAgg._fontd[key] = font
font.clear()
size = prop.get_size_in_points()
font.set_size(size, self.dpi)
return font
示例8: test_afm_kerning
def test_afm_kerning():
from matplotlib.afm import AFM
from matplotlib.font_manager import findfont
fn = findfont("Helvetica", fontext="afm")
with open(fn, 'rb') as fh:
afm = AFM(fh)
assert afm.string_width_height('VAVAVAVAVAVA') == (7174.0, 718)
示例9: _get_font
def _get_font(self, prop):
"""
Find the `FT2Font` matching font properties *prop*, with its size set.
"""
fname = font_manager.findfont(prop)
font = get_font(fname)
font.set_size(self.FONT_SCALE, self.DPI)
return font
示例10: draw_font_table
def draw_font_table(path):
"""
Draw a font table of the first 255 chars of the given font.
Parameters
----------
path : str or None
The path to the font file. If None, use Matplotlib's default font.
"""
if path is None:
path = fm.findfont(fm.FontProperties()) # The default font.
font = FT2Font(path)
# A charmap is a mapping of "character codes" (in the sense of a character
# encoding, e.g. latin-1) to glyph indices (i.e. the internal storage table
# of the font face).
# In FreeType>=2.1, a Unicode charmap (i.e. mapping Unicode codepoints)
# is selected by default. Moreover, recent versions of FreeType will
# automatically synthesize such a charmap if the font does not include one
# (this behavior depends on the font format; for example it is present
# since FreeType 2.0 for Type 1 fonts but only since FreeType 2.8 for
# TrueType (actually, SFNT) fonts).
# The code below (specifically, the ``chr(char_code)`` call) assumes that
# we have indeed selected a Unicode charmap.
codes = font.get_charmap().items()
labelc = ["{:X}".format(i) for i in range(16)]
labelr = ["{:02X}".format(16 * i) for i in range(16)]
chars = [["" for c in range(16)] for r in range(16)]
for char_code, glyph_index in codes:
if char_code >= 256:
continue
row, col = divmod(char_code, 16)
chars[row][col] = chr(char_code)
fig, ax = plt.subplots(figsize=(8, 4))
ax.set_title(path)
ax.set_axis_off()
table = ax.table(
cellText=chars,
rowLabels=labelr,
colLabels=labelc,
rowColours=["palegreen"] * 16,
colColours=["palegreen"] * 16,
cellColours=[[".95" for c in range(16)] for r in range(16)],
cellLoc='center',
loc='upper left',
)
for key, cell in table.get_celld().items():
row, col = key
if row > 0 and col > -1: # Beware of table's idiosyncratic indexing...
cell.set_text_props(fontproperties=fm.FontProperties(fname=path))
fig.tight_layout()
plt.show()
示例11: __enter__
def __enter__(self):
"""
Set matplotlib defaults.
"""
from matplotlib import font_manager, get_backend, rcParams, rcdefaults
import locale
try:
locale.setlocale(locale.LC_ALL, native_str('en_US.UTF-8'))
except:
try:
locale.setlocale(locale.LC_ALL,
native_str('English_United States.1252'))
except:
msg = "Could not set locale to English/United States. " + \
"Some date-related tests may fail"
warnings.warn(msg)
if get_backend().upper() != 'AGG':
import matplotlib
try:
matplotlib.use('AGG', warn=False)
except TypeError:
msg = "Image comparison requires matplotlib backend 'AGG'"
warnings.warn(msg)
# set matplotlib builtin default settings for testing
rcdefaults()
rcParams['font.family'] = 'Bitstream Vera Sans'
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always', 'findfont:.*')
font_manager.findfont('Bitstream Vera Sans')
if w:
warnings.warn('Unable to find the Bitstream Vera Sans font. '
'Plotting tests will likely fail.')
try:
rcParams['text.hinting'] = False
except KeyError:
warnings.warn("could not set rcParams['text.hinting']")
try:
rcParams['text.hinting_factor'] = 8
except KeyError:
warnings.warn("could not set rcParams['text.hinting_factor']")
return self
示例12: test_font_priority
def test_font_priority():
with rc_context(rc={"font.sans-serif": ["cmmi10", "Bitstream Vera Sans"]}):
font = findfont(FontProperties(family=["sans-serif"]))
assert_equal(os.path.basename(font), "cmmi10.ttf")
# Smoketest get_charmap, which isn't used internally anymore
font = get_font(font)
cmap = font.get_charmap()
assert len(cmap) == 131
assert cmap[8729] == 30
示例13: graph
def graph(data, username):
# In order for this to work on Windows, the matplotlib module has to be reimported
# every time; otherwise the script will crash eventually. (Don't ask me why)
import matplotlib.pyplot as plt
from matplotlib import font_manager
font_manager.findfont("Times New Roman")
plt.clf()
N = 24
ind = np.arange(N)
width = 1
p1 = plt.bar(ind, data, width, color="#ccccff", linewidth=1.0)
plt.xlim(0, 24)
plt.ylim(0.00000001, plt.ylim()[1])
chars = max([len(("%f" % t).rstrip("0").rstrip(".")) for t in plt.yticks()[0]])
if chars > 4:
adjustment = 0.019 * (chars - 4)
else:
adjustment = 0.0
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(1, 1, 1)
ax.yaxis.grid(color="black", linestyle="solid", linewidth=1.5)
ax.xaxis.grid(color="black", linestyle="solid", linewidth=1.5)
p1 = plt.bar(ind, data, width, color="#ccccff", linewidth=1.0)
plt.xlim(0, 24)
plt.ylim(0.00000001, plt.ylim()[1])
plt.gcf().subplots_adjust(left=0.125 + adjustment)
plt.xlabel("Time (UTC)")
plt.ylabel("Posts / hour")
plt.title("u/" + username.replace("_", "$\_$"))
plt.xticks(np.arange(25), ("12am", "", "6am", "", "12pm", "", "6pm", "", "12am"))
plt.xticks(np.arange(0, 25, 3))
plt.rcParams.update({"font.size": 22, "font.style": "bold"})
plt.rc("font", family="serif")
plt.rc("font", serif="Times New Roman")
plt.gcf().subplots_adjust(bottom=0.12)
plt.savefig("graph.png")
示例14: _get_font
def _get_font(self, prop):
key = hash(prop)
font = self.fontd.get(key)
if font is None:
fname = findfont(prop)
font = FT2Font(str(fname))
self.fontd[key] = font
font.clear()
size = prop.get_size_in_points()
font.set_size(size, 72.0)
return font
示例15: has_verdana
def has_verdana():
"""Helper to verify if Verdana font is present"""
# This import is relatively lengthy, so to prevent its import for
# testing other tests in this module not requiring this knowledge,
# import font_manager here
import matplotlib.font_manager as mplfm
try:
verdana_font = mplfm.findfont('Verdana', fallback_to_default=False)
except:
# if https://github.com/matplotlib/matplotlib/pull/3435
# gets accepted
return False
# otherwise check if not matching the logic for a 'default' one
try:
unlikely_font = mplfm.findfont("very_unlikely_to_exist1234",
fallback_to_default=False)
except:
# if matched verdana but not unlikely, Verdana must exist
return True
# otherwise -- if they match, must be the same default
return verdana_font != unlikely_font