我正在使用 'ggplot'
样式表。现在,样式很棒,只是我想专门更改字体样式。 这可能吗?
如果找到 documentation关于自定义样式。但是,我只想更改字体,同时保留其余样式。
此外,有谁知道在哪里可以看到每个样式
(如字体、图形大小等)的设置详细信息?
plt.imshow(ori, vmin = 0, vmax = 300)
plt.style.use('ggplot')
plt.show()
最佳答案
组合样式
我认为最优雅的是combine styles .
例如,您可以在 mystyle.mplstyle
中定义您自己的字体设置(请参阅下面的保存位置以及它的外观)。要使用您自己的字体设置获得 ggplot
样式,您只需指定:
plt.style.use(['ggplot', 'mystyle'])
这个解决方案很优雅,因为它允许在所有绘图中应用一致,并允许您混合搭配。
在哪里保存自定义样式?
取 self 自己的一种样式 mystyle.mplstyle
可能有以下条目(显然您应该根据需要自定义):
font.family : serif
font.serif : CMU Serif
font.weight : bold
font.size : 18
text.usetex : true
你应该把它保存在 matplotlib 的配置目录中。对我来说这是~/.matplotlib/stylelib/
,但是使用
import matplotlib
matplotlib.get_configdir()
找出在您的操作系统上使用什么。参见 documentation .您还可以编写一个 Python 函数来安装在正确的位置。
在哪里可以找到现有样式?
然后是你问题的最后一部分。首先,了解您可以使用
获取包含可用样式的列表是很有用的import matplotlib.pyplot as plt
plt.style.available
参见 documentation用于图形表示。
如何检查例如ggplot.mplstyle
?我认为 matplotlib's source 中最好的引用.您还可以在系统上找到 *.mplstyle
文件。但是,在哪里取决于您的操作系统和安装。对我来说
find / -iname 'ggplot.mplstyle' 2>/dev/null
给予
/usr/local/lib/python3.7/site-packages/matplotlib/mpl-data/stylelib/ggplot.mplstyle
或者更一般地说,您可以搜索所有样式:
find / -iname '*.mplstyle' 2>/dev/null
For Windows I am not really an expert, but maybe the file-paths that were listed above give you a clue where to look.
将样式安装到正确位置的 Python 脚本
要在正确的位置安装您的自定义样式,您可以构建一个如下所示的脚本:
def copy_style():
import os
import matplotlib
# style definition(s)
styles = {}
styles['mystyle.mplstyle'] = '''
font.family : serif
'''
# write style definitions
# directory name where the styles are stored
dirname = os.path.abspath(os.path.join(matplotlib.get_configdir(), 'stylelib'))
# make directory if it does not yet exist
if not os.path.isdir(dirname): os.makedirs(dirname)
# write all styles
for fname, style in styles.items():
open(os.path.join(dirname, fname),'w').write(style)
关于python - 使用样式表时自定义字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54706018/