def get_clean_fonts(): """ Return a sane list of fonts for the system that has both regular and bold variants. Pre-pend "default" to the beginning of the list. Returns ------- list: A list of valid fonts for the system """ fmanager = font_manager.FontManager() fonts = dict() for font in fmanager.ttflist: if str(font.weight) in ("400", "normal", "regular"): fonts.setdefault(font.name, dict())["regular"] = True if str(font.weight) in ("700", "bold"): fonts.setdefault(font.name, dict())["bold"] = True valid_fonts = {key for key, val in fonts.items() if len(val) == 2} retval = sorted(list(valid_fonts.intersection(tk_font.families()))) if not retval: # Return the font list with any @prefixed or non-Unicode characters stripped and default # prefixed logger.debug("No bold/regular fonts found. Running simple filter") retval = sorted([fnt for fnt in tk_font.families() if not fnt.startswith("@") and not any([ord(c) > 127 for c in fnt])]) return ["default"] + retval
def show_count_scatterplot(self, data, ax, text_shift=0, text_color='black'): # Scale for font size-- move left to avoid spilling over right axis size_scalar = min(1, 24 / font_manager.FontManager().get_default_size()) pyplot.text(size_scalar * .75, .125 + text_shift, 'Total count: %d' % len(data), color=text_color, transform=ax.transAxes)
def show_correlation_scatterplot(self, data, xcolname, ycolname, ax, text_shift=0, text_color='black'): # Scale for font size-- move left and down to avoid overlap with count size_scalar = min(1, 24 / font_manager.FontManager().get_default_size()) pyplot.text(size_scalar * .75, size_scalar * (.1 + text_shift), 'r = %.4f' % data[xcolname].corr(data[ycolname]), color=text_color, transform=ax.transAxes)
def get_clean_fonts(): """ Return a sane list of fonts for the system that has both regular and bold variants. Pre-pend "default" to the beginning of the list. Returns ------- list: A list of valid fonts for the system """ fmanager = font_manager.FontManager() fonts = dict() for font in fmanager.ttflist: if str(font.weight) in ("400", "normal", "regular"): fonts.setdefault(font.name, dict())["regular"] = True if str(font.weight) in ("700", "bold"): fonts.setdefault(font.name, dict())["bold"] = True valid_fonts = {key for key, val in fonts.items() if len(val) == 2} retval = sorted(list(valid_fonts.intersection(tk_font.families()))) return ["default"] + retval
def __init__(self, url, data_store): self.url = url self.data_store = data_store pres_archive = zipfile.ZipFile(url, 'r') self.styles = BeautifulSoup(pres_archive.read('styles.xml'), \ "lxml", from_encoding='UTF-8') self.content = BeautifulSoup(pres_archive.read('content.xml'), \ "lxml", from_encoding='UTF-8') self.font_mgr = font_manager.FontManager() self.animator = AnimationFactory() self.xml_ids = {} # Create SVG drawing of correct size drawing_size = self.get_document_size() self.d_width = units_to_float(str(drawing_size[0])) self.d_height = units_to_float(str(drawing_size[1])) self.view_box = '0 0 ' + str(self.d_width) + ' ' + str(self.d_height) self.dwg = svgwrite.Drawing(size=drawing_size, viewBox=(self.view_box)) # Setup iterative variables self.clip_id = 0 self.sub_g = 0
import wx.lib.agw.aui as aui import wx.stc as stc from psychopy.localization import _translate from wx import py import keyword import builtins from pathlib import Path from psychopy import prefs from psychopy import logging import psychopy from ...experiment import components import json from matplotlib import font_manager thisFolder = Path(__file__).parent fm = font_manager.FontManager() iconsPath = Path(prefs.paths['resources']) try: FileNotFoundError except NameError: # Py2 has no FileNotFoundError FileNotFoundError = IOError allCompons = components.getAllComponents( ) # ensures that the icons get checked # Create library of "on brand" colours cLib = { 'none': [127, 127, 127, 0], 'black': [0, 0, 0],
def __init__(self, parent, currFont): QDialog.__init__(self, parent) #--------------------- self.currFont = currFont if self.currFont.get_file() == None: self.currFontFile = fm.findfont(self.currFont) self.currFontSize = self.currFont.get_size() self.currFontStyle = self.currFont.get_style() self.currFontWeight = self.currFont.get_weight() self.currFont = fm.FontProperties(fname=self.currFontFile, style=self.currFontStyle, weight=self.currFontWeight, size=self.currFontSize) self.currFontFamily = self.currFont.get_name() else: self.currFontFile = self.currFont.get_file() self.currFontSize = self.currFont.get_size() self.currFontStyle = self.currFont.get_style() self.currFontWeight = self.currFont.get_weight() self.currFontFamily = self.currFont.get_name() self.fontsCacheFile = os.path.expanduser("~") +'/.config/pysoundanalyser/fontsCache' if os.path.exists(self.fontsCacheFile): fIn = open(self.fontsCacheFile, 'rb') self.fontsDic = pickle.load(fIn) fIn.close() else: x = fm.FontManager() weight_lookup = { '100': 'ultralight', '200': 'light', '400': 'normal', '500': 'medium', '600': 'demibold', '700': 'bold', '800': 'extra bold', '900': 'black'} fontList = x.ttflist fontNamesAll = [] for i in range(len(x.ttflist)): fontNamesAll.append(x.ttflist[i].name) fontNames = unique(fontNamesAll) self.fontsDic = {} for i in range(len(fontNames)): self.fontsDic[fontNames[i]] = {} self.fontsDic[fontNames[i]]['style'] = [] self.fontsDic[fontNames[i]]['styleAbb'] = [] for font in fontList: style = font.style weight = font.weight self.fontsDic[font.name]['style'].append(style + ':' + str(weight) + ':' + font.fname) weightName = weight_lookup[str(weight)] styleName = style + ' ' + weightName self.fontsDic[font.name]['styleAbb'].append(styleName) f = open(self.fontsCacheFile, 'wb') pickle.dump(self.fontsDic, f) f.close() #--------------------- self.currLocale = self.parent().prm['data']['currentLocale'] self.currLocale.setNumberOptions(self.currLocale.OmitGroupSeparator | self.currLocale.RejectGroupSeparator) grid = QGridLayout() fontNameLabel = QLabel(self.tr('Font Name')) grid.addWidget(fontNameLabel, 0, 0) fontStyleLabel = QLabel(self.tr('Font Style')) grid.addWidget(fontStyleLabel, 0, 1) fontSizeLabel = QLabel(self.tr('Font Size')) grid.addWidget(fontSizeLabel, 0, 2) ind = sorted(self.fontsDic.keys()).index(self.currFontFamily) self.fontListWidget = QListWidget(self) self.fontListWidget.insertItems(0, sorted(self.fontsDic.keys())) self.fontListWidget.setCurrentRow(ind) self.fontListWidget.itemClicked.connect(self.onChangeFontName) grid.addWidget(self.fontListWidget, 1, 0) self.fontStylesWidget = QListWidget(self) self.fontStylesWidget.insertItems(0, self.fontsDic[sorted(self.fontsDic.keys())[ind]]['styleAbb']) indStyle = self.fontsDic[sorted(self.fontsDic.keys())[ind]]['styleAbb'].index(self.currFontStyle + ' ' + self.currFontWeight) self.fontStylesWidget.setCurrentRow(indStyle) grid.addWidget(self.fontStylesWidget, 1, 1) self.fontSizeWidget = QListWidget(self) self.pointSizeList = ['4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '22', '24', '26', '28', '32', '48', '64', '72', '80', '96', '128'] self.fontSizeWidget.insertItems(0, self.pointSizeList) self.fontSizeWidget.setCurrentRow(self.pointSizeList.index(str(int(self.currFontSize)))) grid.addWidget(self.fontSizeWidget, 1, 2) buttonBox = QDialogButtonBox(QDialogButtonBox.Ok| QDialogButtonBox.Cancel) buttonBox.accepted.connect(self.accept) buttonBox.rejected.connect(self.reject) grid.addWidget(buttonBox, 3, 2) self.setLayout(grid) self.setWindowTitle(self.tr("Choose Font"))
import os import warnings # Suppress warning about subsetting font in PDF file warnings.filterwarnings('ignore', '.*can not be subsetted into a Type 3 font.*') # Use a custom font manager in order to import our local fonts if 'TTFPATH' not in os.environ: os.environ['TTFPATH'] = '../fonts;../../fonts' from matplotlib import font_manager as _fm _fm.fontManager = _fm.FontManager() textwidth = 4.0 # inches; 101.6 mm marginparwidth = 1.41 # inches; 36 mm pagewidth = 5.57 # inches; 141.6 mm import matplotlib as _m import matplotlib.axes import matplotlib.figure import numpy as np import tango # Matplotlib configuration common to all plots in the thesis _m.rc('font', **{ 'family': 'serif', 'serif': 'Minion Pro', 'sans-serif': 'Cantarell, URWClassico, URWClassico-Reg, Optima', 'cursive': 'Lucida Handwriting', 'size': 8}) _m.rc('mathtext', fontset='custom')
def _get_default_font() -> ImageFont: fm = fmgr.FontManager() djv = [x for x in fm.ttffiles if x.endswith('DejaVuSans.ttf')][0] font = ImageFont.truetype(djv, 18) return font
# vim matplotlibrc # 删除 font.family 和 font.sans-serif 两行前的 #, 并在 font.sans-serif 后添加中文字体 Microsoft YaHei, ...(其余不变) # rm -rf ~/.cache/matplotlib/* ################################################################## ## 打印出可用的字体 ## 系统可用中文字体 import subprocess output = subprocess.check_output('fc-list :lang=zh -f "%{family}\n"', shell=True) print('*' * 10, '系统可用的中文字体', '*' * 10) print(output) # 编码有问题 zh_fonts = set(f.split(',', 1)[0] for f in output.decode('utf-8').split('\n')) print(zh_fonts) ## matplotlib 可用所有字体 from matplotlib import font_manager mat_fonts = set(f.name for f in font_manager.FontManager().ttflist) available = mat_fonts & zh_fonts print('*' * 10, '可用的字体', '*' * 10) for f in available: print(f) ## 另一种方法获得 matplotlib 可用所有字体 import pandas as pd fonts = font_manager.findSystemFonts() l = [] for f in fonts: try: font = matplotlib.font_manager.FontProperties(fname=f) l.append((f, font.get_name(), font.get_family(), font.get_weight())) except: pass