本文整理汇总了Python中matplotlib.font_manager.findfont函数的典型用法代码示例。如果您正苦于以下问题:Python findfont函数的具体用法?Python findfont怎么用?Python findfont使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了findfont函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
开发者ID:zoccolan,项目名称:eyetracker,代码行数:11,代码来源:backend_ps.py
示例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
开发者ID:junlysky,项目名称:obspy,代码行数:51,代码来源:testing.py
示例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')
开发者ID:ADSA-UIUC,项目名称:workshop-twitter-bot,代码行数:7,代码来源:test_font_manager.py
示例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")
开发者ID:HubertHolin,项目名称:matplotlib,代码行数:16,代码来源:test_font_manager.py
示例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
开发者ID:4over7,项目名称:matplotlib,代码行数:7,代码来源:backend_svg.py
示例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)
开发者ID:umitceylan,项目名称:Visualizr,代码行数:7,代码来源:test_mathtext.py
示例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
开发者ID:7924102,项目名称:matplotlib,代码行数:25,代码来源:backend_agg.py
示例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)
开发者ID:RealGeeks,项目名称:matplotlib,代码行数:8,代码来源:test_text.py
示例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
开发者ID:QuLogic,项目名称:matplotlib,代码行数:8,代码来源:textpath.py
示例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()
开发者ID:HubertHolin,项目名称:matplotlib,代码行数:57,代码来源:font_table.py
示例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
开发者ID:3rdcycle,项目名称:obspy,代码行数:44,代码来源:testing.py
示例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
开发者ID:CandyCurt,项目名称:matplotlib,代码行数:10,代码来源:test_font_manager.py
示例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")
开发者ID:ClockStalker,项目名称:clockstalker,代码行数:42,代码来源:responder.py
示例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
开发者ID:gkliska,项目名称:razvoj,代码行数:11,代码来源:backend_svg.py
示例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
开发者ID:13052,项目名称:seaborn,代码行数:21,代码来源:test_rcmod.py
示例16: findFont
def findFont(self, props):
from matplotlib.font_manager import FontProperties, findfont
# search for the best match
font = FontProperties( fname=findfont( FontProperties(**props) ) )
props = {
'family' : font.get_name(),
'weight' : font.get_weight(),
'style' : font.get_style(),
}
return props
开发者ID:faunalia,项目名称:ps-speed,代码行数:12,代码来源:graph_settings_dialog.py
示例17: 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 Path(font).name == '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
开发者ID:HubertHolin,项目名称:matplotlib,代码行数:12,代码来源:test_font_manager.py
示例18: plot_trend
def plot_trend(kws, cnts, norm_factors, xlbs, metadata):
'''Trend of a set of keywords.
:param List[str] kws: keywords
:param cnts: counts of keywords
:type cnts: List[List[int]]
:param norm_factors: total number of tweets in each time period
:type norm_factors: List[Int]
:param List[str] xlbs: labels in x-axis
:param metadata: authors and time range in str
:type metadata: List[Object]
'''
fig, ax = plt.subplots()
xs = np.arange(len(xlbs))
plt.xticks(xs, xlbs)
plt.xlim(xs[0]-0.1, xs[-1]+0.1)
xlabels = ax.get_xticklabels()
# limit the number of x-axis labels
show_indices = set(range(len(xlabels))[::len(xlabels)//14+1])
show_indices |= set([len(xlabels)-1])
for i in range(len(xlabels)):
if i not in show_indices:
xlabels[i]._visible = False
xlabels[i].set_rotation(45)
# generate colors for each line
colors = [plt.cm.jet(i) for i in np.linspace(0.1, 0.9, len(kws))]
for kw, cnt, color in zip(kws, cnts, colors):
cnt_normalized = [c / nf if nf != 0 else 0
for c, nf in zip(cnt, norm_factors)]
# make it smooth
xs_new = np.linspace(min(xs), max(xs), 100)
smooth_func = interp1d(xs, cnt_normalized, kind=min(len(xs)-1, 3))
# round the decimal to 5
cnt_smooth = np.around(smooth_func(xs_new), 5)
# no negagive values
cnt_smooth[cnt_smooth < 0] = 0
# limit the word length in legend box
kw = '{}...'.format(kw[:7]) if len(kw) > 10 else kw
ax.plot(xs_new, cnt_smooth, '-', label=kw, color=color)
# place the figure on the left
box = ax.get_position()
ax.set_position([box.x0 - 0.03, box.y0 + 0.15,
box.width * 0.8, box.height * 0.8])
# place the legend on the right
ax.legend(bbox_to_anchor=(1.05, 1.), loc=2, borderaxespad=0.,
prop=fm.FontProperties(fname=fm.findfont('Source Han Sans CN')))
plt.title('{} ngram in {}/{}'.format(', '.join(metadata[0]), *(metadata[1])))
fig.savefig("trend.png")
开发者ID:JoM-Lab,项目名称:JoM,代码行数:52,代码来源:visualize.py
示例19: _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")
fname = findfont(prop)
font = get_font(fname, hinting_factor=rcParams["text.hinting_factor"])
font.clear()
size = prop.get_size_in_points()
font.set_size(size, self.dpi)
return font
开发者ID:Kojoley,项目名称:matplotlib,代码行数:15,代码来源:backend_agg.py
示例20: _get_font
def _get_font(self, prop):
key = hash(prop)
font = self.fontd.get(key)
if font is None:
fname = findfont(prop)
font = self.fontd.get(fname)
if font is None:
#print "Using font",str(fname)
#print type(prop)
font = FT2Font(str(fname))
self.fontd[fname] = font
self.fontd[key] = font
font.clear()
font.set_size(prop.get_size_in_points(), self.dpi)
return font
开发者ID:brefsdal,项目名称:peerplot,代码行数:15,代码来源:rendererh5canvas.py
注:本文中的matplotlib.font_manager.findfont函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论