Python 如何共享matplotlib样式?
可以在Python 如何共享matplotlib样式?,python,matplotlib,Python,Matplotlib,可以在matplotlib中加载自定义打印样式,如下所示: >>> import matplotlib.pyplot as plt >>> plt.style.use('ggplot') 我知道我可以创造我自己的,解释了如何 假设我创建了一个惊人的matplotlib样式——我如何与其他人共享它?有没有办法用pip/conda或其他合适的方法来实现这一点 这些文档包括“创建自定义样式并通过调用style.use和样式表的路径或URL来使用它们”的建议——所以
matplotlib
中加载自定义打印样式,如下所示:
>>> import matplotlib.pyplot as plt
>>> plt.style.use('ggplot')
我知道我可以创造我自己的,解释了如何
假设我创建了一个惊人的matplotlib样式——我如何与其他人共享它?有没有办法用pip/conda或其他合适的方法来实现这一点
这些文档包括“创建自定义样式并通过调用style.use和样式表的路径或URL来使用它们”的建议——所以我想我可以在一些公共git存储库上维护一个链接,如果人们将该URL放在其中,他们会得到最新的样式吗 您可以这样组织代码:
|
└─── setup.py
└─── mplstyles
style_01.mplstyle
style_02.mplstyle
然后,在文件setup.py
中编写如下内容:
# -*- coding: utf-8 -*-
import matplotlib as mpl
import glob
import os.path
import shutil
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-install', action='store_true', default=True)
parser.add_argument('-upgrade', action='store_true')
options = parser.parse_args()
#~ # ref -> matplotlib/style/core
BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib')
STYLE_PATH = os.path.join(os.getcwd(),'mplstyles')
STYLE_EXTENSION = 'mplstyle'
style_files = glob.glob(os.path.join(STYLE_PATH,"*.%s"%(STYLE_EXTENSION)))
for _path_file in style_files:
_, fname = os.path.split(_path_file)
dest = os.path.join(BASE_LIBRARY_PATH, fname)
if not os.path.isfile(dest) and options.install:
shutil.copy(_path_file, dest)
print("%s style installed"%(fname))
elif options.upgrade:
shutil.copy(_path_file, dest)
print("%s style upgraded"%(fname))
elif os.path.isfile(dest):
print("%s style already exists (use -upgrade to upgrade)"%(fname))
else:
pass # ¿?
上面的代码将每个.mplstyle(或样式表)文件从“mplstyles”文件夹复制到Matplotlib安装目录
“安装”样式
“升级”样式
我刚才问了一个完全相同的问题。一件尚未解决的小事。我已经找到了一个解决方案,可以使用PyPi(在我的例子中,也是on)分发样式 我创建了一个Python模块,
mplstyle
-文件是其中的一部分:
|-- setup.py
|-- package_name
| |-- __init__.py
| |-- styles
| | |-- example.mplstyle
现在的想法是:
.mplstyle
文件随模块打包.mplstyle
文件,并将其写入matplotlib config目录>> python setup.py -upgrade
|-- setup.py
|-- package_name
| |-- __init__.py
| |-- styles
| | |-- example.mplstyle
import atexit
from setuptools import setup
from setuptools.command.install import install
def _post_install():
import goosempl
package_name.copy_style()
class new_install(install):
def __init__(self, *args, **kwargs):
super(new_install, self).__init__(*args, **kwargs)
atexit.register(_post_install)
__version__ = '0.1.0'
setup(
name = 'package_name',
version = __version__,
...
install_requires = ['matplotlib>=2.0.0'],
packages = ['package_name'],
cmdclass = {'install': new_install},
package_data = {'package_name/styles':[
'package_name/styles/example.mplstyle',
]},
)
def copy_style():
import os
import matplotlib
from pkg_resources import resource_string
files = [
'styles/example.mplstyle',
]
for fname in files:
path = os.path.join(matplotlib.get_configdir(),fname)
text = resource_string(__name__,fname).decode()
open(path,'w').write(text)