def _delcache(): p1 = matplotlib.get_configdir() + "/fontList.py3k.cache" p2 = matplotlib.get_cachedir() + "/fontList.py3k.cache" p3 = matplotlib.get_configdir() + "/fontList.json" p4 = matplotlib.get_cachedir() + "/fontList.json" for p in [p1, p2, p3, p4]: if os.path.isfile(p): os.remove(p) print("deleted matplotlib font cache:", p) else: print("path not found:", p)
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 install_mpl_style() -> None: """ Will create a `phd.mplstyle` file in the appropriate directories from the `PLOT_PARAMS` defined in this module. This enables one to use the style without importing `PLOT_PARAMS` and updating the rcParams, but instead simply using `plt.style.use("phd")`. Sometimes, matplotlib will not look for the file in its global config directory, but in the activated environment's site-packages data. The file is installed in both places. """ logger.info("Installing matplotlib style") style_content: str = "\n".join(f"{option} : {setting}" for option, setting in PLOT_PARAMS.items()) mpl_config_stylelib = Path(matplotlib.get_configdir()) / "stylelib" mpl_env_stylelib = Path(plt.style.core.BASE_LIBRARY_PATH) logger.debug("Ensuring matplotlib 'stylelib' directory exists") mpl_config_stylelib.mkdir(parents=True, exist_ok=True) mpl_env_stylelib.mkdir(parents=True, exist_ok=True) config_style_file = mpl_config_stylelib / "phd.mplstyle" env_style_file = mpl_env_stylelib / "phd.mplstyle" logger.debug(f"Creating style file at '{config_style_file.absolute()}'") config_style_file.write_text( style_content.replace("(", "").replace(")", "")) logger.debug(f"Creating style file at '{env_style_file.absolute()}'") env_style_file.write_text(style_content.replace("(", "").replace(")", "")) logger.success("You can now use it with 'plt.style.use(\"phd\")'")
def _export_mplstyle(src=pyrolite_datafolder("_config") / "pyrolite.mplstyle", refresh=False): """ Export a matplotlib style file to the matplotlib style library such that one can use e.g. `matplotlib.style.use("pyrolite")`. Parameters ----------- src : :class:`str` | :class:`pathlib.Path` File path for the style file to be exported. refresh : :class:`bool` Whether to re-export a style file (e.g. after updating) even if it already exists in the matplotlib style libary. """ src_fn = Path(src) dest_dir = Path(matplotlib.get_configdir()) / "stylelib" dest_fn = dest_dir / src.name if (not dest_fn.exists()) or refresh: logger.debug( "Exporting pyrolite.mplstyle to matplotlib config folder.") if not dest_dir.exists(): dest_dir.mkdir(parents=True) copy_file(src_fn, dest_dir) # copy to the destination DIR logger.debug("Reloading matplotlib") matplotlib.style.reload_library() # needed to load in pyrolite style NOW
def get_sample_data(fname, asfileobj=True): """ Check the cachedirectory ~/.matplotlib/sample_data for a sample_data file. If it does not exist, fetch it with urllib from the mpl svn repo http://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/sample_data/ and store it in the cachedir. If asfileobj is True, a file object will be returned. Else the path to the file as a string will be returned To add a datafile to this directory, you need to check out sample_data from matplotlib svn:: svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/sample_data and svn add the data file you want to support. This is primarily intended for use in mpl examples that need custom data """ myserver = get_sample_data.myserver if myserver is None: configdir = matplotlib.get_configdir() cachedir = os.path.join(configdir, 'sample_data') baseurl = 'http://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/sample_data/' myserver = get_sample_data.myserver = ViewVCCachedServer(cachedir, baseurl) return myserver.get_sample_data(fname, asfileobj=asfileobj)
def clean_cache(mapdir=None, maxsize=None): """Clean cache directory by checking its size :Params: - **mapdir**, optional: Directory where maps are cached - **maxsize**, optional: Maximal size of directory in bytes. Default value from :confopt:`[vacumm.misc.grid.basemap]max_cache_size` configuration value. """ from ...misc.misc import dirsize mapdir = get_map_dir(mapdir) if mapdir is None: mapdir = os.path.join(get_configdir(), 'basemap', 'cached_maps') cache_size = dirsize(mapdir) if maxsize is None: maxsize = eval(get_config_value('vacumm.misc.grid.basemap', 'max_cache_size')) if cache_size>maxsize: files = [os.path.join(mapdir, ff) for ff in os.listdir(mapdir)] files.sort(cmp=lambda f1, f2: cmp(os.stat(f1)[8], os.stat(f2)[8])) for ff in files: cache_size -= os.path.getsize(ff) try: os.remove(ff) except: vacumm_warn('Error while trying to clean basemap cache in: '+ os.path.dirname(ff)) return if cache_size<=maxsize: break
def _main(): class MplBackendPathFinder(PathFinder): def find_spec(self, fullname, path, target=None): if path == __path__ and fullname.startswith(f"{__name__}."): _, rest = fullname.split(".", 1) for candidate in [f"matplotlib.backends.backend_{rest}", rest]: spec = importlib.util.find_spec(candidate) if spec is not None: def exec_module(module): sys.modules[f"{__name__}.{spec.name}"] = module return type(spec.loader).exec_module( spec.loader, module) spec.loader.exec_module = exec_module return spec return super().find_spec(fullname, path, target) sys.meta_path.append(MplBackendPathFinder()) mplrcpy_path = Path(mpl.get_configdir(), "matplotlibrc.py") try: with tokenize.open(mplrcpy_path) as file: mplrcpy = file.read() except IOError: _log.warning(f"Failed to read {mplrcpy_path}; falling back to " f"automatic backend selection.") else: exec(mplrcpy, {})
def test_install_mplstyles(self): """Install matplotlib style sheets.""" config_dir = os.path.join(mpl.get_configdir(), 'stylelib') if os.path.isdir(config_dir): created_dir = False else: os.mkdir(config_dir) created_dir = True typhon_styles = [ os.path.basename(s) for s in glob.glob(os.path.join('..', 'stylelib', '*.mplstyle')) ] before = set(os.listdir(config_dir)) typhon.plots.install_mplstyles() after = set(os.listdir(config_dir)) for sl in after - before: if sl in typhon_styles: os.remove(os.path.join(config_dir, sl)) if created_dir: os.rmdir(config_dir) assert set(typhon_styles).issubset(set(after))
def _fetch_historical_yahoo(self, ticker, date1, date2, freq=None, cachename=None): """matplotlib's implementation, modified to provide proxy support and frequency Fetch historical data for ticker between date1 and date2. date1 and date2 are date or datetime instances, or (year, month, day) sequences. Ex: fh = fetch_historical_yahoo('^GSPC', (2000, 1, 1), (2001, 12, 31)) cachename is the name of the local file cache. If None, will default to the md5 hash or the url (which incorporates the ticker and date range) a file handle is returned """ if freq is None or type(freq) != str: raise ValueError('Must enter a frequency as a string, m, w, or d') proxy = self._proxy ticker = ticker.upper() configdir = get_configdir() cachedir = os.path.join(configdir, 'finance.cache') if iterable(date1): d1 = (date1[1]-1, date1[2], date1[0]) else: d1 = (date1.month-1, date1.day, date1.year) if iterable(date2): d2 = (date2[1]-1, date2[2], date2[0]) else: d2 = (date2.month-1, date2.day, date2.year) urlFmt = 'http://table.finance.yahoo.com/table.csv?a=%d&b=%d&c=%d&d=%d&e=%d&f=%d&s=%s&y=0&g=%s&ignore=.csv' url = urlFmt % (d1[0], d1[1], d1[2], d2[0], d2[1], d2[2], ticker, freq) if proxy: proxy_support = urllib2.ProxyHandler(proxy) opener = urllib2.build_opener(proxy_support) urllib2.install_opener(opener) if cachename is None: cachename = os.path.join(cachedir, md5(url).hexdigest()) if os.path.exists(cachename): fh = file(cachename) verbose.report('Using cachefile %s for %s'%(cachename, ticker)) else: if not os.path.isdir(cachedir): os.mkdir(cachedir) urlfh = urllib2.urlopen(url) fh = file(cachename, 'w') fh.write(urlfh.read()) fh.close() verbose.report('Saved %s data to cache file %s'%(ticker, cachename)) fh = file(cachename, 'r') return fh
def copy_styles(): """Copy rayoptics mpl styles to user's mpl_config dir.""" pth = Path(__file__).resolve().parent styles_dir = Path(pth / 'styles') mpl_configdir = Path(matplotlib.get_configdir()) / 'stylelib' mpl_configdir.mkdir(exist_ok=True) for mpl_style in styles_dir.glob('*.mplstyle'): copy2(mpl_style, mpl_configdir)
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 copy_styles(): sd = os.path.join(get_configdir(), "stylelib") source = os.path.dirname(os.path.realpath(__file__)) lsd = os.path.join(source, 'arviz', 'plots', 'styles') styles = [f for f in os.listdir(lsd)] if not os.path.isdir(sd): os.makedirs(sd) for s in styles: shutil.copy(os.path.join(lsd, s), os.path.join(sd, s))
def install_style(): style = 'tp.mplstyle' styledir = os.path.join(mpl.get_configdir(), 'stylelib') if not os.path.exists(styledir): os.makedirs(styledir) shutil.copy(os.path.join(os.path.dirname(__file__), style), os.path.join(styledir, style))
def register_style(): ''' Write all goose-styles to the relevant matplotlib configuration directory. ''' import os import matplotlib styles = dict() styles['bhuvy.mplstyle'] = ''' # Main Grids figure.facecolor: F0F8FF patch.antialiased: True # Lines lines.linewidth: 2.0 lines.solid_capstyle: butt # Axes axes.titlesize: 16 axes.labelsize: 12 axes.labelcolor: 000000 axes.facecolor: B2CEE6 axes.edgecolor: 000000 axes.axisbelow: True axes.prop_cycle: cycler('color', ['268BD2', '2AA198', '859900', 'B58900', 'CB4B16', 'DC322F', 'D33682', '6C71C4']) axes.spines.top: False axes.spines.right: False axes.grid: True grid.color: FFFFFF grid.linestyle: - grid.linewidth: 1 xtick.color: 000000 xtick.direction: out ytick.color: 000000 ytick.direction: out # Font font.family: sans-serif font.sans-serif: {} '''.format(find_custom_fonts()) dirname = os.path.abspath( os.path.join(matplotlib.get_configdir(), 'stylelib')) if not os.path.isdir(dirname): os.makedirs(dirname) for fname, style in styles.items(): open(os.path.join(dirname, fname), 'w').write(style)
def install_style(): style = ['tp.mplstyle', 'tp-large.mplstyle'] styledir = os.path.join(get_configdir(), 'stylelib') if not os.path.exists(styledir): os.makedirs(styledir) for plotting in style: copy(os.path.join(os.path.dirname(__file__), plotting), os.path.join(styledir, plotting))
def run(self): import os import matplotlib as mpl os.system('cp -r mplhep/stylelib/ ' + os.path.join(mpl.get_configdir() + '/')) os.system('cp -r mplhep/fonts/ ' + os.path.join(mpl.rcParams['datapath'] + '/')) install.run(self)
def plot_tex(tex=False): mpl.style.reload_library() plt.style.use('zxx') print('find zxx: ', os.path.isfile('zxx.mplstyle')) if (os.path.isfile('zxx.mplstyle')): plt.style.use('zxx.mplstyle') if (tex): plt.style.use('tex') print(plt.style.available) print(mpl.get_configdir())
def Abfragen_Matplotlib(): mpl_version = mpl.__version__ mpl_ort = mpl.__file__ mpl_config = mpl.get_configdir() mpl_cache = mpl.get_cachedir() print("Version von Matplotlib:", mpl_version) print("Installationsort von Matplotlib:", mpl_ort) print("Die Konfigurationsinformationen befinden sich bei:", mpl_config) print("Der Zwischenspeicher / Cache befindet sich bei:", mpl_cache)
def main(): fname = "robertsons_rules.mplstyle" config_dir = mpl.get_configdir() style_dir = os.path.join(config_dir, "stylelib") if not "stylelib" in os.listdir(config_dir): os.mkdir(style_dir) dest = os.path.join(style_dir, fname) shutil.copyfile(fname, dest) print(f"Copied {fname} to {style_dir}")
def makestyle(self, filename='mydefault', to_mpl=False): if filename.startswith('scpy'): error_('`scpy` is READ-ONLY. Please use an another style name.') return txt = "" sline = "" for key in mpl.rcParams.keys(): if key in ['animation.avconv_args', 'animation.avconv_path', 'animation.html_args', 'keymap.all_axes', 'mathtext.fallback_to_cm', 'validate_bool_maybe_none', 'savefig.jpeg_quality', 'text.latex.preview', 'backend', 'backend_fallback', 'date.epoch', 'docstring.hardcopy', 'figure.max_open_warning', 'figure.raise_window', 'interactive', 'savefig.directory', 'timezone', 'tk.window_focus', 'toolbar', 'webagg.address', 'webagg.open_in_browser', 'webagg.port', 'webagg.port_retries']: continue val = str(mpl.rcParams[key]) sav = '' while val != sav: sav = val val = val.replace(' ', ' ') line = f'{key:40s} : {val}\n' if line[0] != sline: txt += '\n' sline = line[0] if key not in ['axes.prop_cycle']: line = line.replace('[', '').replace(']', "").replace('\'', '').replace('"', '') if key == 'savefig.bbox': line = f'{key:40s} : standard\n' txt += line.replace("#", '') # Non matplotlib parameters, # some parameters are not saved in matplotlib style sheets so we willa dd them here nonmplpars = ['method_1D', 'method_2D', 'method_3D', 'colorbar', 'show_projections', 'show_projection_x', 'show_projection_y', 'colormap', 'max_lines_in_stack', 'simplify', 'number_of_x_labels', 'number_of_y_labels', 'number_of_z_labels', 'number_of_contours', 'contour_alpha', 'contour_start', 'antialiased', 'rcount', 'ccount'] txt += '\n\n##\n## ADDITIONAL PARAMETERS FOR SPECTROCHEMPY\n##\n' for par in nonmplpars: txt += f"##@{par:37s} : {getattr(self, par)}\n" stylesheet = (pathclean(self.stylesheets) / filename).with_suffix('.mplstyle') stylesheet.write_text(txt) if to_mpl: # make it also accessible to pyplot stylelib = (pathclean(mpl.get_configdir()) / 'stylelib' / filename).with_suffix('.mplstyle') stylelib.write_text(txt) # plot_preferences.traits()['style'].trait_types = plot_preferences.traits()['style'].trait_types +\ # (Unicode(filename),) self.style = filename return self.style
def creating_new_style(): import matplotlib import os from shutil import copy2 style_path = matplotlib.get_configdir() style_path = os.path.join(style_path, 'stylelib') if not os.path.exists(style_path): os.makedirs(style_path) copy2('presentation.mplstyle', style_path)
def install_styles(): style_files = glob.glob('styles/*.mplstyle', recursive=True) # find stylelib directory, where the *.mplstyle file goes mpl_stylelib_dir = os.path.join(matplotlib.get_configdir(), "stylelib") if not os.path.exists(mpl_stylelib_dir): os.makedirs(mpl_stylelib_dir) # copy files over for style_file in style_files: shutil.copy(style_file, mpl_stylelib_dir)
def _install_matplotlib_styles(self): import matplotlib as mpl conf_dir = mpl.get_configdir() if not os.path.exists(conf_dir): os.mkdir(conf_dir) style_dir = os.path.join(conf_dir, 'stylelib') if not os.path.exists(style_dir): os.mkdir(style_dir) static_path = os.path.join(self._module_path(), 'static', 'styles') for style in os.listdir(static_path): target_path = os.path.join(style_dir, style) if not os.path.exists(target_path): shutil.copyfile(os.path.join(static_path, style), target_path)
def adapt_japanese_font(plt): dest_font_path = Path( mpl.matplotlib_fname()).parent / 'fonts' / 'ttf' / 'ipaexg.ttf' source_font_path = Path(__file__).parent / 'font' / 'ipaexg.ttf' shutil.copy(str(source_font_path), str(dest_font_path)) config_dir = Path(mpl.get_configdir()) for f in config_dir.glob('**/*'): if f.is_file(): f.unlink() else: f.rmdir() plt.rcParams['font.family'] = 'IPAexGothic'
def install_styles(): style_files = glob.glob('styles/**/*.mplstyle', recursive=True) # find stylelib directory, where the *.mplstyle file goes mpl_stylelib_dir = os.path.join(matplotlib.get_configdir(), "stylelib") if not os.path.exists(mpl_stylelib_dir): os.makedirs(mpl_stylelib_dir) # copy files over print(f"Installing styles into {mpl_stylelib_dir}") for style_file in style_files: shutil.copy(style_file, os.path.join(mpl_stylelib_dir, os.path.basename(style_file)))
def install_styles(): # Find all style files stylefiles = glob.glob('styles/**/*.mplstyle', recursive=True) # Find stylelib directory (where the *.mplstyle files go) mpl_stylelib_dir = os.path.join(matplotlib.get_configdir(), "stylelib") if not os.path.exists(mpl_stylelib_dir): os.makedirs(mpl_stylelib_dir) # Copy files over print("Installing styles into", mpl_stylelib_dir) for stylefile in stylefiles: print(os.path.basename(stylefile)) shutil.copy( stylefile, os.path.join(mpl_stylelib_dir, os.path.basename(stylefile)))
def main(): """Put a copy of the matplotlib style spec in the expected location.""" this_dir = os.path.dirname(os.path.realpath(__file__)) style_path = os.path.join(this_dir, 'civis.mplstyle') with open(style_path) as f: style_doc = f.read() mpl_style_dir = os.path.join(mpl.get_configdir(), 'stylelib') if not os.path.exists(mpl_style_dir): os.makedirs(mpl_style_dir) path = os.path.join(mpl_style_dir, 'civis.mplstyle') with open(path, 'w') as new_style: new_style.write(style_doc) print("The Civis matplotlib style was installed at %s" % path)
def copy_style(): import os import matplotlib from pkg_resources import resource_string files = [ 'styles/notebook_mplstyle', ] for fname in files: path = os.path.join(matplotlib.get_configdir(), fname) text = resource_string(__name__, fname).decode() open(path, 'w').write(text)
def copy_style(): import os import matplotlib from pkg_resources import resource_string files = [ "college_track.mplstyle", ] for fname in files: path = os.path.join(matplotlib.get_configdir(), fname) text = resource_string(__name__, fname).decode() open(path, "w").write(text)
def install_stylesheet(): stylelib = os.path.join(mpl.get_configdir(), 'stylelib') # in case you don't have a stylelib directory yet try: os.mkdir(stylelib) except FileExistsError: pass try: filepath = resource_filename('gpviz', 'styles/gpviz.mplstyle') except ModuleNotFoundError: filepath = resource_filename(__name__, 'styles/gpviz.mplstyle') shutil.copy(filepath, stylelib)
def copy_plot_themes(): stylelib_path = os.path.join(matplotlib.get_configdir(), 'stylelib') curr_dir = os.path.dirname(os.path.abspath(__file__)) file_list = glob.glob(os.path.join(curr_dir, '*.mplstyle')) try: if not os.path.exists(stylelib_path): os.makedirs(stylelib_path) for f in file_list: fname = os.path.basename(f) shutil.copy2(f, os.path.join(stylelib_path, fname)) print('Themes copied to %s' % stylelib_path) except: print( 'An error occured! Try to manually copy the *.mplstyle files. E.g.:\nmkdir -p %s && cp *.mplstyle %s' % (stylelib_path, stylelib_path), )
def copy_style(): import os import matplotlib from pkg_resources import resource_string files = [ 'stylelib/goose-latex.mplstyle', 'stylelib/goose-tick-in.mplstyle', 'stylelib/goose-tick-lower.mplstyle', 'stylelib/goose.mplstyle', ] for fname in files: path = os.path.join(matplotlib.get_configdir(), fname) text = resource_string(__name__, fname).decode() open(path, 'w').write(text)
def write_style_file(name): local_stylelib_dir = os.path.join(mpl.get_configdir(), 'stylelib') os.makedirs(local_stylelib_dir, exist_ok=True) local_file = os.path.join(local_stylelib_dir, f'{name}.mplstyle') package_file = os.path.join(get_qncmbe_stylelib_dir(), f'{name}.mplstyle') with open(local_file, 'w') as lf: lf.write(get_header() + '\n') with open(package_file, 'r') as pf: lf.write(pf.read()) logger.info(f'Wrote to style file "{local_file}"') plt.style.reload_library()
def get_sample_data(fname, asfileobj=True): """ Check the cachedirectory ~/.matplotlib/sample_data for a sample_data file. If it does not exist, fetch it with urllib from the mpl svn repo http://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/sample_data/ and store it in the cachedir. If asfileobj is True, a file object will be returned. Else the path to the file as a string will be returned To add a datafile to this directory, you need to check out sample_data from matplotlib svn:: svn co https://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/sample_data and svn add the data file you want to support. This is primarily intended for use in mpl examples that need custom data """ myserver = get_sample_data.myserver if myserver is None: configdir = matplotlib.get_configdir() cachedir = os.path.join(configdir, 'sample_data') baseurl = 'http://matplotlib.svn.sourceforge.net/svnroot/matplotlib/trunk/sample_data/' get_sample_data.myserver = ViewVCCachedServer(cachedir, baseurl) myserver = get_sample_data.myserver return myserver.get_sample_data(fname, asfileobj=asfileobj)
def clean_cache(mapdir=None, maxsize=None): """Clean cache directory by checking its size :Params: - **mapdir**, optional: Directory where maps are cached - **maxsize**, optional: Maximal size of directory in bytes. Default value from :confopt:`[vacumm.misc.grid.basemap]max_cache_size` configuration value. """ from ...misc.misc import dirsize mapdir = get_map_dir(mapdir) if mapdir is None: mapdir = os.path.join(get_configdir(), 'basemap', 'cached_maps') cache_size = dirsize(mapdir) if maxsize is None: maxsize = eval(get_config_value('vacumm.misc.grid.basemap', 'max_cache_size')) if cache_size>maxsize: files = [os.path.join(mapdir, ff) for ff in os.listdir(mapdir)] files.sort(cmp=lambda f1, f2: cmp(os.stat(f1)[8], os.stat(f2)[8])) for ff in files: cache_size -= os.path.getsize(ff) os.remove(ff) if cache_size<=maxsize: break
def findfont(self, prop, fontext='ttf'): """Search the font dictionary for a font that exactly or closely matches the specified font properties. See the FontProperties class for a description. The properties are searched in the following order: name, style, variant, weight, stretch, and size. The font weight always matches returning the closest weight, and the font size always matches for scalable fonts. An oblique style font will be used inplace of a missing italic style font if present. See the W3C Cascading Style Sheet, Level 1 (CSS1; http://www.w3.org/TR/1998/REC-CSS2-19980512/) documentation for a description of the font finding algorithm. """ cache_message = \ """Saving AFM font cache for PS backend to %s. Delete this file to have matplotlib rebuild the cache.""" debug = False if prop.fname is not None: fname = prop.fname verbose.report('findfont returning %s'%fname, 'debug') return fname if fontext == 'afm': if len(self.afmdict) == 0: afmcache = os.path.join(get_configdir(), '.afmfont.cache') try: import cPickle as pickle except ImportError: import pickle try: self.afmdict = pickle.load(file(afmcache)) except: self.afmdict = createFontDict(self.afmfiles, fontext='afm') pickle.dump(self.afmdict, file(afmcache, 'w')) verbose.report(cache_message % afmcache) fontdict = self.afmdict else: fontdict = self.ttfdict name = prop.get_family()[0] style = prop.get_style() variant = prop.get_variant() weight = weight_as_number(prop.get_weight()) stretch = prop.get_stretch() size = str(prop.get_size_in_points()) try: fname = fontdict[name][style][variant][weight][stretch][size] verbose.report('\tfindfont cached %(name)s, %(style)s, %(variant)s, %(weight)s, %(stretch)s, %(size)s'%locals(), 'debug') verbose.report('findfont returning %s'%fname, 'debug') return fname except KeyError: pass for name in prop.get_family(): font = fontdict if font.has_key(name): font = font[name] else: verbose.report('\tfindfont failed %(name)s'%locals(), 'debug') continue if font.has_key(style): font = font[style] elif style == 'italics' and font.has_key('oblique'): font = font['oblique'] else: verbose.report('\tfindfont failed %(name)s, %(style)s'%locals(), 'debug') continue if font.has_key(variant): font = font[variant] else: verbose.report('\tfindfont failed %(name)s, %(style)s, %(variant)s'%locals(), 'debug') continue if not font.has_key(weight): setWeights(font) font = font[weight] # !!!! need improvement if font.has_key(stretch): font = font[stretch] else: verbose.report('\tfindfont failed %(name)s, %(style)s, %(variant)s %(weight)s, %(stretch)s'%locals(), 'debug') continue if font.has_key('scalable'): fname = font['scalable'] elif font.has_key(size): fname = font[size] else: verbose.report('\tfindfont failed %(name)s, %(style)s, %(variant)s %(weight)s, %(stretch)s, %(size)s'%locals(), 'debug') continue fontkey = FontKey(name, style, variant, weight, stretch, size) add_filename(fontdict, fontkey, fname) verbose.report('\tfindfont found %(name)s, %(style)s, %(variant)s %(weight)s, %(stretch)s, %(size)s'%locals(), 'debug') verbose.report('findfont returning %s'%fname, 'debug') return fname fontkey = FontKey(name, style, variant, weight, stretch, size) add_filename(fontdict, fontkey, self.defaultFont) warnings.warn('Could not match %s, %s, %s. Returning %s' % (name, style, variant, self.defaultFont)) return self.defaultFont
def __init__(self, size=12.0, weight='normal'): self.__default_size = size self.__default_weight = weight paths = [rcParams['datapath']] # Create list of font paths for pathname in ['TTFPATH', 'AFMPATH']: if os.environ.has_key(pathname): ttfpath = os.environ[pathname] if ttfpath.find(';') >= 0: #win32 style paths.extend(ttfpath.split(';')) elif ttfpath.find(':') >= 0: # unix style paths.extend(ttfpath.split(':')) else: paths.append(ttfpath) verbose.report('font search path %s'%(str(paths))) # Load TrueType fonts and create font dictionary. self.ttffiles = findSystemFonts(paths) + findSystemFonts() for fname in self.ttffiles: verbose.report('trying fontname %s' % fname, 'debug') if fname.lower().find('vera.ttf')>=0: self.defaultFont = fname break else: # use anything self.defaultFont = self.ttffiles[0] cache_message = \ """Saving TTF font cache for non-PS backends to %s. Delete this file to have matplotlib rebuild the cache.""" oldcache = os.path.join(get_home(), 'ttffont.cache') ttfcache = os.path.join(get_configdir(), 'ttffont.cache') if os.path.exists(oldcache): print >> sys.stderr, 'Moving old ttfcache location "%s" to new location "%s"'%(oldcache, ttfcache) shutil.move(oldcache, ttfcache) try: import cPickle as pickle except ImportError: import pickle def rebuild(): self.ttfdict = createFontDict(self.ttffiles) pickle.dump(self.ttfdict, file(ttfcache, 'w')) verbose.report(cache_message % ttfcache) try: self.ttfdict = pickle.load(file(ttfcache)) except: rebuild() else: # verify all the cached fnames still exist; if not rebuild for fname in ttfdict_to_fnames(self.ttfdict): if not os.path.exists(fname): rebuild() break verbose.report('loaded ttfcache file %s'%ttfcache) #self.ttfdict = createFontDict(self.ttffiles) # Load AFM fonts for PostScript # Only load file names at this stage, the font dictionary will be # created when needed. self.afmfiles = findSystemFonts(paths, fontext='afm') + \ findSystemFonts(fontext='afm') self.afmdict = {}
import datetime import numpy as np from matplotlib import verbose, get_configdir from matplotlib.dates import date2num from matplotlib.cbook import iterable, mkdirs from matplotlib.collections import LineCollection, PolyCollection from matplotlib.colors import colorConverter from matplotlib.lines import Line2D, TICKLEFT, TICKRIGHT from matplotlib.patches import Rectangle from matplotlib.transforms import Affine2D configdir = get_configdir() # cachedir will be None if there is no writable directory. if configdir is not None: cachedir = os.path.join(configdir, 'finance.cache') else: # Should only happen in a restricted environment (such as Google App # Engine). Deal with this gracefully by not caching finance data. cachedir = None stock_dt = np.dtype([('date', object), ('year', np.int16), ('month', np.int8), ('day', np.int8), ('d', np.float), # mpl datenum ('open', np.float),
if __name__=='__main__': referenceLabel='Delivered'#from which label,lumi unit should be calculated labels=['Delivered','Recorded']#default label order allowedActions = ['run','time','fill','perday','instpeakperday'] beamChoices=['PROTPHYS','IONPHYS','PAPHYS'] allowedscales=['linear','log','both'] beamModeChoices = [ "stable", "quiet", "either"] amodetagChoices = [ "PROTPHYS","IONPHYS",'PAPHYS' ] actiontofilebasemap={'time':'lumivstime','run':'lumivsrun','fill':'lumivsfill','perday':'lumiperday','instpeakperday':'lumipeak'} # # parse figure configuration if found # currentdir=os.getcwd() rcparamfile='.lumiplotrc' mplrcdir=matplotlib.get_configdir() mpllumiconfig=os.path.join(mplrcdir,rcparamfile) locallumiconfig=os.path.join(currentdir,rcparamfile) figureparams={'sizex':7.5,'sizey':5.7,'dpi':135} if os.path.exists(locallumiconfig): import ConfigParser try: config=ConfigParser.RawConfigParser() config.read(locallumiconfig) figureparams['sizex']=config.getfloat('sizex') figureparams['sizey']=config.getfloat('sizey') figureparams['dpi']=config.getint('dpi') except ConfigParser.NoOptionError: pass elif os.path.exists(mpllumiconfig): import ConfigParser
import jupyter_core.paths import matplotlib as mpl # Root directory of repository (where this file is located) root_dir = os.path.realpath(os.path.dirname(__file__)) # Get IPython configuration directory ipython_dir = IPython.paths.get_ipython_dir() # Destination directories for each source directory # (except IPython, which depends on the profile to be used...) dest_dirs = { '.ipython': ipython_dir, '.jupyter': jupyter_core.paths.jupyter_config_dir(), '.matplotlib': mpl.get_configdir(), } # Proper function to get raw input from user in Python 2 or 3 if sys.version_info.major == 2: get_input = raw_input else: get_input = input # Symbolic link function for unix vs windows try: symlink = os.symlink except AttributeError:
# https://www.datacamp.com/community/tutorials/machine-learning-python import numpy as np from sklearn import datasets digits = datasets.load_digits() #print(digits) import matplotlib from sklearn.decomposition import RandomizedPCA from sklearn.decomposition import PCA print "config dir=", matplotlib.get_configdir() matplotlib.use('TkAgg') # the same dataset as above but from another location #import pandas as pd #digits = pd.read_csv("http://archive.ics.uci.edu/ml/machine-learning-databases/optdigits/optdigits.tra", header=None) print " ---- KEYS ------" print digits.keys() print " ---- DATA ----" print digits.data print " == DESCR ===" #print digits.DESCR # Isolate the `digits` data digits_data = digits.data print "there are 1797 samples and that there are 64 features " # Inspect the shape print(digits_data.shape) # Isolate the target values with `target`
from numpy import * import scipy.constants as con from scipy.ndimage.filters import median_filter from matplotlib.pyplot import * import matplotlib.patches as patches import matplotlib.image as mpimg import profile from matplotlib import rc import dm3lib_v099 as dm3 print matplotlib.get_configdir() print args, fullpath # with file('log.txt', 'w') as outfile: # outfile.write('# Args\n') # outfile.write(str(args)) rc("savefig", dpi=600) rc("xtick", direction="out") rc("ytick", direction="out") rc("lines", markeredgewidth=1) print "Welcome to Diffraction Ring Profiler. This program will measure electron diffraction rings" print " and extract intensity profiles from the diffraction pattern."
import os import sys from os.path import join, exists, expanduser import matplotlib as mpl mplrc_dir = mpl.get_configdir() if sys.platform.startswith('linux'): mplrc_dir = expanduser('~/.config/matplotlib') # To conform with the XDG base directory standard, # this configuration location has been deprecated on Linux, # and the new location is now '/home/joncrall/.config'/matplotlib/. # Please move your configuration there to ensure that matplotlib will # continue to find it in the future. mplrc_fpath = join(mplrc_dir, 'matplotlibrc') mplrc_text = ''' backend : qt4agg ''' if not exists(mplrc_dir): os.makedirs(mplrc_dir) with open(mplrc_fpath, 'w') as file_: file_.write(mplrc_text) print('wrote %r' % mplrc_fpath)
# -*- coding:utf8 -*- import matplotlib as mpl print mpl.rcParams print len(mpl.rcParams) mpl.rc('lines', linewidth=2, color='r') print mpl.get_configdir()
def get_map_dir(mapdir=None): """Get the directory where cqched maps are stored""" if mapdir is None: mapdir = os.path.join(get_configdir(), 'basemap', 'cached_maps') return mapdir
def findfont(prop, fontext='ttf'): if not is_string_like(prop): prop = prop.get_fontconfig_pattern() cached = _fc_match_cache.get(prop) if cached is not None: return cached result = fc_match(prop, fontext) if result is None: result = fc_match(':', fontext) _fc_match_cache[prop] = result return result else: _fmcache = os.path.join(get_configdir(), 'fontManager.cache') fontManager = None def _rebuild(): global fontManager fontManager = FontManager() pickle_dump(fontManager, _fmcache) verbose.report("generated new fontManager") try: fontManager = pickle_load(_fmcache) fontManager.default_size = None verbose.report("Using fontManager instance from %s" % _fmcache) except: _rebuild()
return None _fc_match_regex = re.compile(r'\sfile:\s+"([^"]*)"') _fc_match_cache = {} def findfont(prop, fontext='ttf'): if not is_string_like(prop): prop = prop.get_fontconfig_pattern() cached = _fc_match_cache.get(prop) if cached is not None: return cached result = fc_match(prop, fontext) if result is None: result = fc_match(':', fontext) _fc_match_cache[prop] = result return result else: _fmcache = os.path.join(get_configdir(), 'fontList.cache') fontManager = None def _rebuild(): global fontManager fontManager = FontManager() pickle_dump(fontManager, _fmcache) verbose.report("generated new fontManager") try: fontManager = pickle_load(_fmcache) if (not hasattr(fontManager, '_version') or fontManager._version != FontManager.__version__): _rebuild() else: fontManager.default_size = None verbose.report("Using fontManager instance from %s" % _fmcache) except:
import contextlib import os import re import warnings import matplotlib as mpl from matplotlib import rc_params_from_file, rcParamsDefault from matplotlib.cbook import MatplotlibDeprecationWarning __all__ = ['use', 'context', 'available', 'library', 'reload_library'] BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib') # Users may want multiple library paths, so store a list of paths. USER_LIBRARY_PATHS = [os.path.join(mpl.get_configdir(), 'stylelib')] STYLE_EXTENSION = 'mplstyle' STYLE_FILE_PATTERN = re.compile(r'([\S]+).%s$' % STYLE_EXTENSION) # A list of rcParams that should not be applied from styles STYLE_BLACKLIST = { 'interactive', 'backend', 'backend.qt4', 'webagg.port', 'webagg.address', 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback', 'toolbar', 'timezone', 'datapath', 'figure.max_open_warning', 'savefig.directory', 'tk.window_focus', 'docstring.hardcopy'} def _remove_blacklisted_style_params(d, warn=True): o = {} for key, val in d.items():
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 os import shutil import matplotlib as mpl stylelib = os.path.join(mpl.get_configdir(), 'stylelib') # in case you don't have a stylelib directory yet try: os.mkdir(stylelib) except FileExistsError: pass # copy the files into the stylelib directory [shutil.copy(f, stylelib) for f in os.listdir('.') if f.endswith('.mplstyle')]
""" Created on Jun 12, 2015 precisa colocar o argumento py2exe @author: Paloschi """ import matplotlib matplotlib.use("Agg") # overrule configuration print(matplotlib.get_configdir()) from distutils.core import setup import py2exe Mydata_files = [("images", ["images/icons/icon_trator.png"])] setup( windows=["CyMP.py"], data_files=(matplotlib.get_py2exe_datafiles()), options={ "py2exe": { # "dll_excludes" : [], "dll_excludes": [ "MSVCP90.dll", "HID.DLL", "api-ms-win-core-processthreads-l1-1-2.dll", "api-ms-win-core-delayload-l1-1-1.dll", "api-ms-win-core-errorhandling-l1-1-1.dll", "api-ms-win-core-sysinfo-l1-2-1.dll", "api-ms-win-core-heap-l2-1-0.dll", "api-ms-win-core-profile-l1-1-0.dll",
from __future__ import division import numpy as np import pandas as pd import matplotlib matplotlib.get_configdir() matplotlib.use('Agg') # Must be before importing matplotlib.pyplot or pylab! import matplotlib.pyplot as plt from pylab import * from matplotlib import rcParams from scipy import integrate # Getting SVN number GIT= # Help to find the fonts properly! # You can find the list of fonts installed on the system with: #fonts = "\n".join(matplotlib.font_manager.findSystemFonts(fontpaths=None, fontext="ttf")) #print fonts # If Times New Roman is listed in the system, check if it is listed in python: #print [f.name for f in matplotlib.font_manager.fontManager.ttflist] # Maybe the python package have its own fonts folder, find it and add the file times.ttf # Then, you need to remove the fontmanager cache so the code will read the new file # Find the cache location with: #print matplotlib.get_cachedir() # Defining fonts to be used in plots rcParams.update({'figure.autolayout': True}) rcParams.update({'font.family':'Times New Roman'}) rcParams.update({'font.size':20})