def test_user_fonts_win32(): if not (os.environ.get('APPVEYOR', False) or os.environ.get('TF_BUILD', False)): pytest.xfail("This test should only run on CI (appveyor or azure) " "as the developer's font directory should remain " "unchanged.") font_test_file = 'mpltest.ttf' # Precondition: the test font should not be available fonts = findSystemFonts() if any(font_test_file in font for font in fonts): pytest.skip(f'{font_test_file} already exists in system fonts') user_fonts_dir = MSUserFontDirectories[0] # Make sure that the user font directory exists (this is probably not the # case on Windows versions < 1809) os.makedirs(user_fonts_dir) # Copy the test font to the user font directory shutil.copy(Path(__file__).parent / font_test_file, user_fonts_dir) # Now, the font should be available fonts = findSystemFonts() assert any(font_test_file in font for font in fonts)
def set_style(style_filename_list): # graph_font_filename = resource_filename(__name__, os.path.join("fonts", "Roboto-Medium.ttf")) # WORKAROUND: createFontList deprecation in mpl >=3.2 if hasattr(fm.fontManager, "addfont"): font_dirs = [ resource_filename(__name__, "fonts"), ] font_files = fm.findSystemFonts(fontpaths=font_dirs) for font_found in font_files: fm.fontManager.addfont(font_found) else: font_dirs = [ resource_filename(__name__, "fonts"), ] font_files = fm.findSystemFonts(fontpaths=font_dirs) font_list = fm.createFontList(font_files) fm.fontManager.ttflist.extend(font_list) fm.fontManager.ttflist = font_list styles_in_final_location = list() for source_name in style_filename_list: styles_in_final_location.append( resource_filename(__name__, os.path.join("mpl_styles", source_name))) # fm.FontProperties(fname=graph_font_filename) matplotlib.style.use(styles_in_final_location)
def test_user_fonts(): if not os.environ.get('APPVEYOR', False): pytest.xfail('This test does only work on appveyor since user fonts ' 'are Windows specific and the developer\'s font ' 'directory should remain unchanged') font_test_file = 'mpltest.ttf' # Precondition: the test font should not be available fonts = findSystemFonts() assert not any(font_test_file in font for font in fonts) user_fonts_dir = MSUserFontDirectories[0] # Make sure that the user font directory exists (this is probably not the # case on Windows versions < 1809) os.makedirs(user_fonts_dir) # Copy the test font to the user font directory shutil.copyfile(os.path.join(os.path.dirname(__file__), font_test_file), os.path.join(user_fonts_dir, font_test_file)) # Now, the font should be available fonts = findSystemFonts() assert any(font_test_file in font for font in fonts)
def test_user_fonts_win32(): if not os.environ.get('APPVEYOR', False): pytest.xfail('This test does only work on appveyor since user fonts ' 'are Windows specific and the developer\'s font ' 'directory should remain unchanged') font_test_file = 'mpltest.ttf' # Precondition: the test font should not be available fonts = findSystemFonts() if any(font_test_file in font for font in fonts): pytest.skip(f'{font_test_file} already exists in system fonts') user_fonts_dir = MSUserFontDirectories[0] # Make sure that the user font directory exists (this is probably not the # case on Windows versions < 1809) os.makedirs(user_fonts_dir) # Copy the test font to the user font directory shutil.copyfile(os.path.join(os.path.dirname(__file__), font_test_file), os.path.join(user_fonts_dir, font_test_file)) # Now, the font should be available fonts = findSystemFonts() assert any(font_test_file in font for font in fonts)
def set_style(style_filename_list, can_use_cjk=True): # graph_font_filename = resource_filename(__name__, os.path.join("fonts", "Roboto-Medium.ttf")) # WORKAROUND: createFontList deprecation in mpl >=3.2 if hasattr(fm.fontManager, "addfont"): font_dirs = [ resource_filename(__name__, "fonts"), ] font_files = fm.findSystemFonts(fontpaths=font_dirs) for font_found in font_files: fm.fontManager.addfont(font_found) else: font_dirs = [ resource_filename(__name__, "fonts"), ] font_files = fm.findSystemFonts(fontpaths=font_dirs) font_list = fm.createFontList(font_files) fm.fontManager.ttflist.extend(font_list) fm.fontManager.ttflist = font_list styles_in_final_location = list() for source_name in style_filename_list: styles_in_final_location.append( resource_filename(__name__, os.path.join("mpl_styles", source_name))) # fm.FontProperties(fname=graph_font_filename) # Apply style matplotlib.style.use(styles_in_final_location) # NEW: support for CJK characters, apply override after setting the style if config["General"].getint("use_cjk_font") != 0 and can_use_cjk: plt.rcParams['font.family'] = 'Noto Sans CJK JP'
def set_style(style_name: str = 'default'): """ Sets colors, fonts, font sizes, bounding boxes, and more for plots using pyplot. .. note:: The font sizes of the predefined styles will be overwritten! .. seealso:: https://matplotlib.org/users/customizing.html https://matplotlib.org/tutorials/introductory/customizing.html#matplotlib-rcparams https://matplotlib.org/api/_as_gen/matplotlib.pyplot.rc.html https://matplotlib.org/users/usetex.html https://stackoverflow.com/questions/11367736/matplotlib-consistent-font-using-latex :param style_name: str containing the matplotlib style name, or 'default' for the Pyrado default style """ try: font_manager.findSystemFonts(fontpaths=None, fontext='ttf') font_manager.findfont('serif', rebuild_if_missing=False) except Exception: pass if style_name == 'default': plt.rc('font', family='serif') plt.rc('text', usetex=False) plt.rc('text.latex', preamble=r"\usepackage{lmodern}") # direct font input plt.rc('mathtext', fontset='cm') plt.rc('pgf', rcfonts=False ) # to use the LaTeX document's fonts in the PGF plots plt.rc('image', cmap='inferno') # default: viridis plt.rc('legend', frameon=False) plt.rc('legend', framealpha=0.4) plt.rc('axes', xmargin=0.) # disable margins by default elif style_name == 'ggplot': plt.style.use('ggplot') elif style_name == 'dark_background': plt.style.use('dark_background') elif style_name == 'seaborn': plt.style.use('seaborn') elif style_name == 'seaborn-muted': plt.style.use('seaborn-muted') else: ValueError( "Unknown style name! Got {}, but expected 'default', 'ggplot', 'dark_background'," "'seaborn', or 'seaborn-muted'.".format(style_name)) plt.rc('font', size=10) plt.rc('xtick', labelsize=10) plt.rc('ytick', labelsize=10) plt.rc('savefig', bbox='tight' ) # 'tight' is incompatible with pipe-based animation backends plt.rc('savefig', pad_inches=0)
def plot_similarity(): # region Setting font for matplotlib font_dirs = [ 'C:\\Users\\NSL\\Downloads\\Nanum_Gothic\\', ] font_files = font_manager.findSystemFonts(fontpaths=font_dirs) font_list = font_manager.createFontList(font_files) font_manager.fontManager.ttflist.extend(font_list) mpl.rcParams['font.family'] = 'NanumGothic' # endregion words = [] embeddings = [] similarities = Embeddings.objects.all() for similarity in similarities: words.append(similarity.text) np_bytes = base64.b64decode(similarity.embedding) embeddings.append(pickle.loads(np_bytes)) pca = PCA(n_components=2) result = pca.fit_transform(embeddings) plt.scatter(result[:, 0], result[:, 1]) for i, word in enumerate(words): plt.annotate(word, xy=(result[i, 0], result[i, 1])) plt.savefig("plot.png", dpi=1000)
def __init__(self, font_name='', font_dirs='', x_label='', y_label=''): self.fig = plt.figure(figsize=(3.3, 3.3)) self.ax = self.fig.add_subplot(111) # Change font properties or add custom fonts if font_name != '': ''' Solution found at: https://stackoverflow.com/questions/35668219/\ how-to-set-up-a-custom-font-with-custom-path-to-matplotlib-global-font ''' self.font = font_name font_files = fm.findSystemFonts(fontpaths=font_dirs) font_list = fm.createFontList(font_files) fm.fontManager.ttflist.extend(font_list) plt.rcParams['font.family'] = self.font self.title_font_sz = 8 self.ticks_font_size = 7 plt.rcParams.update({'font.size': self.ticks_font_size}) # Define axes labels self.ax.set_xlabel(x_label, labelpad=5, fontsize=self.title_font_sz) self.ax.set_ylabel(y_label, labelpad=5, fontsize=self.title_font_sz) # Define markers and colours self.markers = [ '8', '>', 'D', '^', 'H', '*', 'd', 'h', 'v', 's', '<', 'o', 'p' ] colormap = plt.cm.get_cmap('brg') self.colours = [ colormap(i) for i in np.linspace(0, 0.9, len(self.ax.collections)) ] return
def _pys2fonts(self, line): """Updates custom font list""" font_name, ascii_font_data = self._split_tidy(line) font_data = base64.b64decode(ascii_font_data) # Get system font names system_fonts = font_manager.findSystemFonts() system_font_names = [] for sys_font in system_fonts: system_font_names.append( font_manager.FontProperties(fname=sys_font).get_name()) # Use the system font if applicable if font_name not in system_font_names: self.code_array.custom_fonts[font_name] = font_data with open(self.temp_fontdir + os.sep + font_name, "wb") as font_file: font_file.write(font_data) with tempfile.NamedTemporaryFile() as fontsconf_tmpfile: fontsconf_tmpfile_name = fontsconf_tmpfile.name fontsconf_tmpfile.write(self.temp_fontdir) os.environ["FONTCONFIG_FILE"] = fontsconf_tmpfile_name
def test_get_font_names(): paths_mpl = [cbook._get_data_path('fonts', subdir) for subdir in ['ttf']] fonts_mpl = findSystemFonts(paths_mpl, fontext='ttf') fonts_system = findSystemFonts(fontext='ttf') ttf_fonts = [] for path in fonts_mpl + fonts_system: try: font = ft2font.FT2Font(path) prop = ttfFontProperty(font) ttf_fonts.append(prop.name) except: pass available_fonts = sorted(list(set(ttf_fonts))) mpl_font_names = sorted(fontManager.get_font_names()) assert len(available_fonts) == len(mpl_font_names) assert available_fonts == mpl_font_names
def radar(self):#绘制雷达图,涉及变量为11个中排除调式剩下的10个,标准化后的极径范围为0-1 # 导入中文 font_dirs = ['./font'] font_files = font_manager.findSystemFonts(fontpaths=font_dirs) font_list = font_manager.createFontList(font_files) font_manager.fontManager.ttflist.extend(font_list) plt.rcParams['font.family'] = 'SimHei' feature=['danceability','energy','valence','tempo','loudness','key','acousticness','instrumentalness','liveness','speechiness','danceability'] # 启用主题 plt.style.use('ggplot') #等分图 angles = np.linspace(0, 2 * np.pi, 10, endpoint=False) #角度首尾封闭 angles = np.append(angles, angles[0]) #数据首尾封闭 values = np.append(np.array(self.figure), self.data[2]) fig=plt.figure() # 设置为极坐标格式 ax = fig.add_subplot(111, polar=True) ax.plot(angles, values, 'o-', linewidth=2) # 填充颜色 ax.fill(angles, values, alpha=0.25) ax.set_thetagrids(angles * 180 / np.pi, feature) plt.title('radar') ax.set_ylim(0, 1.1) # 添加网格线 ax.grid(True) plt.show()
def set_style(style='white', palette='deep', context='poster', font='FreeSans', font_scale=1.00): """Set plot preference in a way that looks good to me. """ import matplotlib.font_manager as font_manager import cycler # Update font list. mpl_data_dir = os.path.dirname(mpl.matplotlib_fname()) font_files = font_manager.findSystemFonts( os.path.join(mpl_data_dir, 'fonts', 'ttf')) font_list = font_manager.createFontList(font_files) font_manager.fontManager.ttflist.extend(font_list) sns.set( style=style, palette=palette, context=context, font=font, font_scale=font_scale, ) scale_dict = {'paper': 1.3, 'notebook': 1.3, 'talk': 1.4, 'poster': 1.4} scale = scale_dict[context] plt.rc('axes', linewidth=1.33, labelsize=14) plt.rc('xtick', labelsize=10 * scale) plt.rc('ytick', labelsize=10 * scale) plt.rc('xtick', bottom=True) plt.rc('xtick.major', size=5 * scale, width=1.33) plt.rc('xtick.minor', size=5 * scale, width=1.33) plt.rc('ytick', left=True) plt.rc('ytick.major', size=5 * scale, width=1.33) plt.rc('ytick.minor', size=5 * scale, width=1.33) plt.rc('legend', fontsize=7 * scale) plt.rc('grid', color='grey', linewidth=0.5, alpha=0.33) plt.rc('font', family=font) color_palette = [ '#005AC8', '#AA0A3C', '#0AB45A', '#FA7850', '#8214A0', '#FA78FA', '#A0FA82', '#006E82', '#00A0FA', '#14D2DC', '#F0F032', '#FAE6BE', ] mpl.rcParams['axes.prop_cycle'] = cycler.cycler(color=color_palette)
def check_font(): flist = font_manager.findSystemFonts() names = [ font_manager.FontProperties(fname=fname).get_name() for fname in flist ] if not (FONT_NAME in names): font_manager._rebuild()
def findFontFiles(self, folders=(), recursive=True): """Search for font files in the folder (or system folders) Parameters ---------- folders: iterable folders to search. If empty then search typical system folders Returns ------- list of pathlib.Path objects """ if sys.platform == 'win32': searchPaths = [] # just leave it to matplotlib as below elif sys.platform == 'darwin': # on mac matplotlib doesn't include 'ttc' files (which are fine) searchPaths = _OSXFontDirectories elif sys.platform.startswith('linux'): searchPaths = _X11FontDirectories # search those folders fontPaths = [] for thisFolder in searchPaths: thisFolder = Path(thisFolder) for thisExt in supportedExtensions: if recursive: fontPaths.extend([str(p.absolute()) for p in thisFolder.rglob("*.{}".format(thisExt))]) else: fontPaths.extend([str(p.absolute()) for p in thisFolder.glob("*.{}".format(thisExt))]) # if we failed let matplotlib have a go if fontPaths: return fontPaths else: from matplotlib import font_manager return font_manager.findSystemFonts()
def find_font(keyword): pattern = re.compile(".*" + keyword + ".*") all_fonts = fm.findSystemFonts() for font in all_fonts: if (pattern.search(font)): return (font) return (None)
def CF(itemList, keyList): """Change font given item""" # initialize fontprop object fontprop = fm.FontProperties(style='normal', weight='normal', stretch='normal') if os.path.isfile(fontname): # check if font is a file fontprop.set_file(fontname) else: # check if the name of font is available in the system if not any([ fontname.lower() in a.lower() for a in fm.findSystemFonts(fontpaths=None, fontext='ttf') ]): print('Cannot find specified font: %s' % (fontname)) fontprop.set_family(fontname) # set font name # set font for each object for n, item in enumerate(itemList): if isinstance(fontsize, dict): if keyList[n] in fontsize.keys(): fontprop.set_size(fontsize[keyList[n]]) else: pass # print('Warning font property {} not in specified fontsize. Font is kept at defualt.'.format(keyList[n])) elif n < 1: # set the properties only once fontprop.set_size(fontsize) item.set_fontproperties(fontprop) # change font for all items
def __init__(self): # Get a list of fonts we want to render in. self.all_fonts = fm.findSystemFonts() print("Found %d system fonts." % len(self.all_fonts)) # Make the temporary storage directory if needed. if not os.path.exists(constants.DATA_DIR): os.makedirs(constants.DATA_DIR)
def plt_setup(dark=False): # clear existing plots plt.ioff() plt.close('all') plt.cla() plt.clf() mpl.rcdefaults() # resets seaborn # load Open Sans - which is referred to from matplotlib.rc font_files = fm.findSystemFonts(fontpaths=['./fonts/Open_Sans']) for font_file in font_files: fm.fontManager.addfont(font_file) mpl_rc_path = './src/matplotlib.rc' mpl.rc_file(mpl_rc_path) if dark: dark_col = '#2e2e2e' text_col = 'lightgrey' mpl.rcParams['axes.facecolor'] = dark_col mpl.rcParams['figure.facecolor'] = dark_col mpl.rcParams['savefig.facecolor'] = dark_col mpl.rcParams['text.color'] = text_col mpl.rcParams['axes.edgecolor'] = text_col mpl.rcParams['axes.labelcolor'] = text_col mpl.rcParams['xtick.color'] = text_col mpl.rcParams['ytick.color'] = text_col mpl.rcParams['grid.color'] = text_col
def _pys2fonts(self, line): """Updates custom font list""" font_name, ascii_font_data = self._split_tidy(line) font_data = base64.b64decode(ascii_font_data) print font_name # Get system font names system_fonts = font_manager.findSystemFonts() system_font_names = [] for sys_font in system_fonts: system_font_names.append( font_manager.FontProperties(fname=sys_font).get_name() ) # Use the system font if applicable if font_name not in system_font_names: self.code_array.custom_fonts[font_name] = font_data with open(self.temp_fontdir + os.sep + font_name, "wb") as font_file: font_file.write(font_data) with tempfile.NamedTemporaryFile() as fontsconf_tmpfile: fontsconf_tmpfile_name = fontsconf_tmpfile.name fontsconf_tmpfile.write(self.temp_fontdir) os.environ["FONTCONFIG_FILE"] = fontsconf_tmpfile_name
def japanize(): font_dir_path = get_font_path() font_dirs = [font_dir_path] font_files = font_manager.findSystemFonts(fontpaths=font_dirs) font_list = font_manager.createFontList(font_files) font_manager.fontManager.ttflist.extend(font_list) matplotlib.rc('font', family=FONT_NAME)
def getFontStyleList(self, ): from matplotlib import font_manager font_manager._rebuild() # 리스트의 원소(폰트파일의 경로)만큼 반복 fontDict = dict({}) for v in font_manager.findSystemFonts(fontpaths=None, fontext='ttf'): try: # 각 폰트파일의 경로를 사용하여 폰트 속성 객체 얻기 fprop = font_manager.FontProperties(fname=v) # 폰트 속성중 이름과 파일 경로를 딕셔러리로 구성하여 리스트에 추가. fontDict[fprop.get_name()] = fprop.get_file() except: continue fontDict = dict(sorted(fontDict.items())) #sort key newFontDict = dict({}) for key in fontDict.keys(): newFontDict["""<span style="font-family:""" + key + """;">""" + key + "</span>"] = fontDict[ key] #apply font style on display fontDict = newFontDict #<span style="font-family:Ami R;">Ami R</span> fontDict["NotoSans"] = "./font/NotoSansKR-Regular.otf" return newFontDict
def set_font(font): """set graph text font """ if font not in plt.rcParams["font.family"]: font_manager.fontManager.ttflist.extend( font_manager.createFontList(font_manager.findSystemFonts())) plt.rcParams["font.family"] = font
def plt_show(model, img_name="plt.png"): ## Visualize Word Embedding from sklearn.decomposition import PCA import matplotlib.pyplot as plt import matplotlib as mpl import matplotlib.font_manager as fm print('버전: ', mpl.__version__) print('설치 위치: ', mpl.__file__) print('설정 위치: ', mpl.get_configdir()) print('캐시 위치: ', mpl.get_cachedir()) font_list = fm.findSystemFonts(fontpaths=None, fontext='ttf') [ print((f.name, f.fname)) for f in fm.fontManager.ttflist if 'Nanum' in f.name ] path = '/Users/actmember/Library/Fonts/NanumBarunGothic.otf' fontprop = fm.FontProperties(fname=path, size=8) mpl.rcParams['axes.unicode_minus'] = False X = model[model.wv.vocab] pca = PCA(n_components=2) result = pca.fit_transform(X) # create a scatter plot of the projection plt.scatter(result[:, 0], result[:, 1]) words = list(model.wv.vocab) for i, word in enumerate(words): plt.annotate(word, xy=(result[i, 0], result[i, 1]), fontproperties=fontprop) plt.savefig(img_name, quality=100, dpi=500) plt.show()
def updateFontInfo(self,monospace_only=True): self._available_font_info.clear() del self.font_family_styles[:] import matplotlib.font_manager as font_manager font_paths=font_manager.findSystemFonts() def createFontInfo(fp,fface): fns=(fface.family_name,fface.style_name) if fns in self.font_family_styles: pass else: self.font_family_styles.append((fface.family_name,fface.style_name)) styles_for_font_dict=self._available_font_info.setdefault(fface.family_name,{}) fonts_for_style=styles_for_font_dict.setdefault(fface.style_name,[]) fi=FontInfo(fp,fface) fonts_for_style.append(fi) for fp in font_paths: if os.path.isfile(fp) and os.path.exists(fp): try: face=Face(fp) if monospace_only: if face.is_fixed_width: createFontInfo(fp,face) else: createFontInfo(fp,face) except Exception, e: logging.debug('Error during FontManager.updateFontInfo(): %s\nFont File: %s'%(str(e),fp))
def extend_matplotlib_fonts(font_directory): """Facilitates the use of external fonts for use in matplotlib. Currently dependent on a deprecated function. Suggested matplotlib.font_manager.FontManager.addfont method does not appear to give expected results.""" font_dirs = [font_directory] font_files = fm.findSystemFonts(fontpaths=font_dirs) font_list = fm.createFontList(font_files) fm.fontManager.ttflist.extend(font_list)
def get_matplotlib_info(): print('버전: ', mpl.__version__) print('설치 위치: ', mpl.__file__) print('설정 위치: ', mpl.get_configdir()) print('캐시 위치: ', mpl.get_cachedir()) print('설정 파일 위치: ', mpl.matplotlib_fname()) font_list = fm.findSystemFonts(fontpaths=None, fontext='ttf') print(len(font_list))
def add_custom_fonts(): ''' Allow us to use fonts from our fonts folder ''' font_dirs = ['fonts'] font_files = font_manager.findSystemFonts(fontpaths=font_dirs) font_list = font_manager.createFontList(font_files) font_manager.fontManager.ttflist.extend(font_list)
def __init__(self, complexity): self.rand = None # random numbr generator self.cardSize = (7.08, 2.165) # in inches, std business card for AUS # work out which chars we'll use self.complexity = complexity lc = [chr(I) for I in np.arange(97, 123)] uc = [chr(I) for I in np.arange(65, 91)] num = [chr(I) for I in np.arange(48, 58)] punc = [chr(I) for I in np.arange(33, 48)] + [ chr(I) for I in np.arange(58, 65) ] + [chr(I) for I in np.arange(94, 97) ] + [chr(I) for I in np.arange(123, 127)] if self.complexity == 1: self.chars = lc self.punc = [] elif self.complexity == 2: self.chars = lc + num self.punc = [] elif self.complexity == 3: self.chars = lc + uc + num self.punc = [] elif self.complexity == 4: self.chars = lc + uc + num self.punc = punc self.puncAmnt = 1 # 10% punctuation else: # self.complexity == 5 or ??? self.chars = lc + uc + num + punc self.punc = [] # set the font # try to find source code pro self.fProps = [ font_manager.FontProperties(), font_manager.FontProperties() ] sf = font_manager.findSystemFonts() bold = None reg = None for i in sf: if string.find(i, 'SourceCodePro-Bold.ttf') != -1: bold = font_manager.FontProperties(fname=i) if string.find(i, 'SourceCodePro-Regular.ttf') != -1: reg = font_manager.FontProperties(fname=i) if bold is not None: if reg is not None: self.fProps = [reg, bold] else: self.fProps = [bold, bold] else: if reg is not None: self.fProps = [reg, reg] # stick with 5 colors self.cols = ['#66A61E', '#E7298A', '#7570B3', '#D95F02', '#1B9E77']
def get_system_fonts(): """Return sorted list of all system font names.""" fonts = set() for x in font_manager.findSystemFonts(): dot = x.rfind('.') slash = x.rfind(sep) x = x[slash + 1:dot] fonts.add(x) return sorted(fonts)
def install_fonts_to_matplotlib(): fonts_folder = os.path.join(home, '.fonts') font_dirs = [fonts_folder] font_files = font_manager.findSystemFonts(fontpaths=font_dirs) font_list = font_manager.createFontList(font_files) font_manager.fontManager.ttflist.extend(font_list) matplotlib.rcParams['font.family'] = 'Roboto'
def verify_plotting_packages(): """Verifies that all the plotting packages are installed. Otherwise, install the missing one. """ # Import the fonts font_dirs = [os.path.dirname(os.path.realpath(__file__)) + '/fonts/'] font_files = font_manager.findSystemFonts(fontpaths=font_dirs) for font_file in font_files: font_manager.fontManager.addfont(font_file)
def _set_common_parameters(fontsize, **kwargs): # japanese font # --------------------------------------- fonts = fm.findSystemFonts() for font in fonts: font_name = fm.FontProperties(fname=font).get_name() if font_name == 'Noto Sans CJK JP': plt.rcParams['font.family'] = font_name print("{:s} is found".format(font_name)) break # if font_name == 'Noto Sans Mono CJK JP': # plt.rcParams['font.family'] = font_name # print("{:s} is found".format(font_name)) # break # font size # --------------------------------------- if fontsize: plt.rcParams["font.size"] = fontsize if 'tick_size' in kwargs and kwargs['tick_size']: plt.rcParams['xtick.labelsize'] = kwargs['tick_size'] plt.rcParams['ytick.labelsize'] = kwargs['tick_size'] if 'xtick_size' in kwargs and kwargs['xtick_size']: plt.rcParams['xtick.labelsize'] = kwargs['xtick_size'] if 'ytick_size' in kwargs and kwargs['ytick_size']: plt.rcParams['ytick.labelsize'] = kwargs['ytick_size'] if 'axis_label_size' in kwargs and kwargs['axis_label_size']: plt.rcParams['axes.labelsize'] = kwargs['axis_label_size'] if 'graph_title_size' in kwargs and kwargs['graph_title_size']: plt.rcParams['axes.titlesize'] = kwargs['graph_title_size'] if 'legend_size' in kwargs and kwargs['legend_size']: plt.rcParams['legend.fontsize'] = kwargs['legend_size'] # plot style # --------------------------------------- if 'grid' in kwargs: if kwargs['grid']: plt.rcParams['axes.grid'] = True else: plt.rcParams['axes.grid'] = False else: plt.rcParams['axes.grid'] = True # line style # --------------------------------------- if 'linewidth' in kwargs and kwargs['linewidth']: plt.rcParams['lines.linewidth'] = kwargs['linewidth'] if 'prop_cycle' in kwargs and kwargs['prop_cycle']: plt.rcParams['axes.prop_cycle'] = kwargs['prop_cycle']
def font_selection(self, font_folder='fonts', font='Helvetica LT Std'): # Using Helvetica as a font font_folder = self.font_folder font_dirs = [ font_folder, ] font_files = font_manager.findSystemFonts(fontpaths=font_dirs) for p in font_files: font_manager.fontManager.addfont(p) matplotlib.rcParams['font.family'] = font
def get_system_fonts() -> List[str]: """get_system_fonts will get a list of all the fonts (.ttf) from the system Returns: List[str]: List of all the fonts """ matches = list( filter(lambda path: str(path).lower().endswith('.ttf'), fontman.findSystemFonts())) matches = sorted(matches) return matches
def find_times_font(bold=False, italic=False): fonts = findSystemFonts() for fontpath in fonts: fprop = FontProperties(fname=fontpath) name = fprop.get_name() name_matched = 'Times New Roman' in name pname = os.path.splitext(os.path.basename(fontpath))[0] style_matched = ((not bold) or (bold and (pname.endswith('Bold') or (pname.lower() == pname and pname.endswith('bd'))))) and \ ((not italic) or (italic and (pname.endswith('Italic') or (pname.lower() == pname and pname.endswith('i'))))) if name_matched and style_matched: return fprop return None
def __init__(self, complexity): self.rand = None # random numbr generator self.cardSize = (7.08, 2.165) # in inches, std business card for AUS # work out which chars we'll use self.complexity = complexity lc = [chr(I) for I in np.arange(97, 123)] uc = [chr(I) for I in np.arange(65, 91)] num = [chr(I) for I in np.arange(48, 58)] punc = [chr(I) for I in np.arange(33, 48)] + [chr(I) for I in np.arange(58, 65)] + [chr(I) for I in np.arange(94, 97)] + [chr(I) for I in np.arange(123, 127)] if self.complexity == 1: self.chars = lc self.punc = [] elif self.complexity == 2: self.chars = lc + num self.punc = [] elif self.complexity == 3: self.chars = lc + uc+ num self.punc = [] elif self.complexity == 4: self.chars = lc + uc + num self.punc = punc self.puncAmnt = 1 # 10% punctuation else: # self.complexity == 5 or ??? self.chars = lc + uc + num + punc self.punc = [] # set the font # try to find source code pro self.fProps = [font_manager.FontProperties(), font_manager.FontProperties()] sf = font_manager.findSystemFonts() bold = None reg = None for i in sf: if string.find(i, 'SourceCodePro-Bold.ttf') != -1: bold = font_manager.FontProperties(fname=i) if string.find(i, 'SourceCodePro-Regular.ttf') != -1: reg = font_manager.FontProperties(fname=i) if bold is not None: if reg is not None: self.fProps = [reg, bold] else: self.fProps = [bold, bold] else: if reg is not None: self.fProps = [reg, reg] # stick with 5 colors self.cols = ['#66A61E', '#E7298A', '#7570B3', '#D95F02', '#1B9E77']
def test_user_fonts_linux(tmpdir, monkeypatch): font_test_file = 'mpltest.ttf' # Precondition: the test font should not be available fonts = findSystemFonts() if any(font_test_file in font for font in fonts): pytest.skip(f'{font_test_file} already exists in system fonts') # Prepare a temporary user font directory user_fonts_dir = tmpdir.join('fonts') user_fonts_dir.ensure(dir=True) shutil.copyfile(Path(__file__).parent / font_test_file, user_fonts_dir.join(font_test_file)) with monkeypatch.context() as m: m.setenv('XDG_DATA_HOME', str(tmpdir)) _call_fc_list.cache_clear() # Now, the font should be available fonts = findSystemFonts() assert any(font_test_file in font for font in fonts) # Make sure the temporary directory is no longer cached. _call_fc_list.cache_clear()
def build_fontbank(self): # load fonts self.font_set = font_manager.findSystemFonts(fontpaths=None, fontext="ttf") self.successful_caches = {} self.successful_caches_names = {} # initialize directory, process fonts mkdir(self.cache_dir) self.font_name = {} self.font_family = {} self.font_subfamily = {} for f in self.font_set: data = self.fontInfo(f) self.font_name[f] = data[0] self.font_family[f] = data[1] self.font_subfamily[f] = data[2] self.cache_all_fonts()
def CF(itemList, keyList): """Change font given item""" # initialize fontprop object fontprop = fm.FontProperties(style='normal', weight='normal', stretch = 'normal') if os.path.isfile(fontname): # check if font is a file fontprop.set_file(fontname) else:# check if the name of font is available in the system if not any([fontname.lower() in a.lower() for a in fm.findSystemFonts(fontpaths=None, fontext='ttf')]): print('Cannot find specified font: %s' %(fontname)) fontprop.set_family(fontname) # set font name # set font for each object for n, item in enumerate(itemList): if isinstance(fontsize, dict): fontprop.set_size(fontsize[keyList[n]]) elif n <1: # set the properties only once fontprop.set_size(fontsize) item.set_fontproperties(fontprop) # change font for all items
def __defaultImgFont(): preferreds = ("msjh.ttc", #winxp "arialuni.ttf", #win7 "ukai.ttc", #ubuntu "arial unicode.ttf") #mac def is_preferred(name): name = os.path.basename(name).lower() return name in preferreds # NOTICE! need patch font_manager.py to let ttf support ttc format fonts = font_manager.findSystemFonts(fontpaths=None, fontext='ttf') #for font in fonts: #print(font) pref_fonts = [ font for font in fonts if is_preferred(font)] font = pref_fonts[0] if pref_fonts else fonts[0] logging.info("Default Image Font: %s" % font) return font
def _fonts2pys(self): """Writes fonts to pys file""" # Get mapping from fonts to fontfiles system_fonts = font_manager.findSystemFonts() font_name2font_file = {} for sys_font in system_fonts: font_name = font_manager.FontProperties(fname=sys_font).get_name() if font_name in self.fonts_used: font_name2font_file[font_name] = sys_font # Only include fonts that have been used in the attributes for font_name in font_name2font_file: # Serialize font with open(font_name2font_file[font_name]) as fontfile: font_data = fontfile.read() ascii_font_data = base64.b64encode(font_data) # Store font in pys file font_line_list = [font_name, ascii_font_data] self.pys_file.write(u"\t".join(font_line_list) + u"\n")
def __init__(self, *args): QPushButton.__init__(self, *args) self._app = QApplication.instance().window self.textOptions = Property.TextOptions() # Set initial textOptions values based on application preferences if 'preferences' in self._app.__dict__.keys(): preferenceTextOptions = self._app.preferences.getInternal('textOptions') if preferenceTextOptions is not None: self.setTextOptions(preferenceTextOptions) # Create dialog self._dialog = QTextOptionsWidget(self) self._ui = Ui_TextOptionsWidget() self._ui.setupUi(self._dialog) self._dialog.setUiObject(self._ui) self._window = SubWindow(self._app.ui.workspace) self._window.setWidget(self._dialog) self._dialog.setParent(self._window) self.hideTextOptionsWidget() # Create font list from matplotlib fonts fontPropList = fm.createFontList(fm.findSystemFonts()) # Get just the names fontList = map(lambda x:x.name, fontPropList) # Unique and sort the names fontList = list(set(fontList)) fontList.sort() # Enter fonts into the ui widget self._ui.name.addItems(fontList)
def updateFontInfo(self,monospace_only=True): self._available_font_info.clear() del self.font_family_styles[:] self.addFontFiles(font_manager.findSystemFonts(),monospace_only)
from matplotlib.figure import Figure from matplotlib.text import Text from matplotlib.path import Path from matplotlib import _png, rcParams from matplotlib import font_manager from matplotlib.ft2font import FT2Font from matplotlib.cbook import is_string_like, is_writable_file_like from matplotlib.compat import subprocess from matplotlib.compat.subprocess import check_output ############################################################################### # create a list of system fonts, all of these should work with xe/lua-latex system_fonts = [] for f in font_manager.findSystemFonts(): try: system_fonts.append(FT2Font(str(f)).family_name) except RuntimeError: pass # some fonts on osx are known to fail, print? except: pass # unknown error, skip this font def get_texcommand(): """Get chosen TeX system from rc.""" texsystem_options = ["xelatex", "lualatex", "pdflatex"] texsystem = rcParams.get("pgf.texsystem", "xelatex") return texsystem if texsystem in texsystem_options else "xelatex"
def _find_font_file(query): """Utility to find font file. """ return list(filter(lambda path: query.lower() in os.path.basename(path).lower(), fontman.findSystemFonts()))
def rand_font(fonts=[], fontpaths=None, fontext='ttf', font_encoding='', min_size=24, max_size=36): if fonts == []: fonts = findSystemFonts(fontpaths, fontext) requested_font = fonts[random.randint(0, len(fonts)-1)] font_size = random.randint(min_size, max_size) return ImageFont.truetype(requested_font, font_size, encoding=font_encoding)
_path = get_data_path() faces = ('mit', 'rm', 'tt', 'cal', 'nonascii') filenamesd = {} fonts = {} # Filling the above dicts for face in faces: # The filename without the path barefname = rcParams['mathtext.' + face] base, ext = os.path.splitext(barefname) if not ext: ext = '.ttf' barefname = base + ext # First, we search for the font in the system font dir for fname in findSystemFonts(fontext=ext[1:]): if fname.endswith(barefname): filenamesd[face] = fname break # We check if the for loop above had success. If it failed, we try to # find the font in the mpl-data dir if not face in filenamesd: filenamesd[face] = os.path.join(_path, barefname) fonts[face] = FT2Font(filenamesd[face]) svg_elements = Bunch(svg_glyphs=[], svg_lines=[]) esc_char = '\\' # Grouping delimiters begin_group_char = '{' end_group_char = '}'
from numpy.random import * from matplotlib import pyplot as plt import matplotlib as mpl import matplotlib.font_manager as fm print(mpl.get_configdir()) print(fm.findSystemFonts()) # 乱数生成 rand_nums = randn(100) # 追加部分 フォントを指定する。 plt.rcParams["font.family"] = "IPAexGothic" # ヒストグラム表示 plt.hist(rand_nums) plt.xlabel("X軸と表示したい") plt.ylabel("Y軸と表示したい") plt.show()
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 df = pd.DataFrame(l, columns=['path', 'name', 'family', 'weight']) print(df) # 我的电脑竟然有近 500 个字体 ################################################################## ## 测试 x = np.arange(1, 11); y = 2 * x + 5 plt.plot(x, y, "ob"); plt.title("你好") plt.show()
#test import matplotlib.font_manager as fm import pandas as pd fonts=fm.findSystemFonts() for f in sorted(fonts): font=fm.FontProperties(fname=f) print(font.get_name()) #"HGSeikaishotaiPRO"
def SimpleBarPlot(groups, values, errors, savepath=None, width = 0.27, size=(3, 3), color=['#1f77b4']): """Takes 3 inputs and generate a simple bar plot e.g. groups = ['dog','cat','hippo'] values = [15, 10, 3] errors = [0.5, 0.3, 0.8] savepath: path to save figure. Format will be parsed by the extension of save name width: distance between each bars size: figure size, in inches. Input as a tuple. Default (3,3) color: default tableau10's steelblue color (hex: #1f77b4) """ # Get bar plot function according to style ngroups = len(groups) # group labels # leftmost position of bars pos = np.arange(ngroups) # initialize the plot fig, axs = plt.subplots(nrows=1, ncols = 1, sharex=True) # plot the series axs.bar(pos, values, width, yerr=errors, color=color, align='center') # set axis axs.tick_params(axis='both',direction='out') axs.spines['left'].set_visible(True) axs.spines['right'].set_visible(False) axs.spines['top'].set_visible(False) axs.spines['bottom'].set_visible(True) axs.xaxis.set_ticks_position('bottom') axs.yaxis.set_ticks_position('left') ymin, ymax = axs.get_ybound() if ymax <= 0.0: # only negative data present # flip label to top axs.spines['bottom'].set_position('zero') # zero the x axis axs.tick_params(labelbottom=False, labeltop=True) elif ymin >= 0.0: # only positive data present. Default axs.spines['bottom'].set_position('zero') # zero the x axis else: # mix of positive an negative data : set all label to bottoms axs.spines['bottom'].set_visible(False) axs.spines['top'].set_visible(True) axs.spines['top'].set_position('zero') axs.xaxis.set_ticks_position('none') # Set x categorical label x = range(0,len(groups)) if axs.get_xlim()[0] >= x[0]: axs.set_xlim(axs.get_xticks()[0]-1,axs.get_xlim()[-1]) if axs.get_xlim()[-1] <= x[-1]: axs.set_xlim(axs.get_xlim()[0], axs.get_xticks()[-1]+1) plt.xticks(x, groups) # Set font itemDict = {'title':[axs.title], 'xlab':[axs.xaxis.label], 'ylab':[axs.yaxis.label], 'xtick':axs.get_xticklabels(), 'ytick':axs.get_yticklabels(), 'texts':axs.texts if isinstance(axs.texts, np.ndarray) or isinstance(axs.texts, list) else [axs.texts], 'legend': [] if axs.legend_ is None else axs.legend_.get_texts(), 'legendtitle':[] if axs.legend_ is None else [axs.legend_.get_title()]} itemList, keyList = [], [] for k, v in iter(itemDict.items()): itemList += v keyList += [k]*len(v) # initialize fontprop object fontprop = fm.FontProperties(style='normal', weight='normal', stretch = 'normal') if os.path.isfile(fontname): # check if font is a file fontprop.set_file(fontname) else:# check if the name of font is available in the system if not any([fontname.lower() in a.lower() for a in fm.findSystemFonts(fontpaths=None, fontext='ttf')]): print('%s font not found. Use system default.' %(fontname)) fontprop.set_family(fontname) # set font name # set font for each object for n, item in enumerate(itemList): if isinstance(fontsize, dict): fontprop.set_size(fontsize[keyList[n]]) elif n <1: # set the properties only once fontprop.set_size(fontsize) item.set_fontproperties(fontprop) # change font for all items # Set figure size fig.set_size_inches(size[0],size[1]) # Save the figure if savepath is not None: fig.savefig(savepath, bbox_inches='tight', rasterized=True, dpi=300) return(fig, axs)
def load_system_fonts(): from matplotlib.font_manager import findSystemFonts fonts = findSystemFonts() families = {get_font_family(font) for font in fonts} for family in families: try_load_font_mpl(family)