使用 Matplot Lib 将字体属性设置为刻度标签 [英] Set Font Properties to Tick Labels with Matplot Lib

查看:31
本文介绍了使用 Matplot Lib 将字体属性设置为刻度标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将带有matplotlib的刻度标签的字体从标准字体更改为Times New Roman.我认为这应该与更改标题和轴标签的字体一样简单,但事实证明这有点棘手.目前,我只是想为x-tick标签设置字体,这些标签是自动格式化的日期(这可能是我的问题之一,但我不确定).

I'm trying to change the font of tick labels with matplotlib from the standard font to Times New Roman. I think this should be as easy as changing the font for the title and axis labels, but it's proving to be a little tricky. Currently, I'm just trying to set the font for the x-tick labels, which are dates that are autoformatted (which may be one of my problems, but I'm not sure).

当运行下面的相关代码片段时,我收到错误Axessubplot 没有属性‘set_fontproperties’".

I get the error "no attribute 'set_fontproperties' for Axessubplot" when the relevant snippets of code below are run.

ticks_font = matplotlib.font_manager.FontProperties(family='times new roman', style='normal', size=12, weight='normal', stretch='normal')

fig.autofmt_xdate()
ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
for label in ax.get_xticklabels():
    ax.set_fontproperties(ticks_font)

非常感谢任何帮助.

谢谢.

更新/啊,我觉得自己像个傻瓜.刚刚想通了,一旦我意识到它就变得如此明显.在上面的代码段中,答案是:

Update/ Ah, I feel like a goof. Just figured it out and it was so obvious once I realized it. In the context of the snippet above, the answer is:

label.set_fontproperties(ticks_font)

推荐答案

如果您正在运行脚本,您还可以在运行命令之前使用参数列表设置它.如以下摘自我的脚本:

You can also set it before running the command with a parameter list if your running a script. Such as below taken from a script of mine:

fig_size = [fig_width, fig_height] 
tick_size = 9
fontlabel_size = 10.5
params = {
    'backend': 'wxAgg',
    'lines.markersize' : 2,
    'axes.labelsize': fontlabel_size,
    'text.fontsize': fontlabel_size,
    'legend.fontsize': fontlabel_size,
    'xtick.labelsize': tick_size,
    'ytick.labelsize': tick_size,
    'text.usetex': True,
    'figure.figsize': fig_size
}
plt.rcParams.update(params)

或者,如果您想像执行此操作那样运行,则请运行:

Or if you want to do it like you had it then run:

for label in ax.get_xticklabels() :
    label.set_fontproperties(ticks_font)

它正在获取每个标签,其中包含您可以为其设置的所有文本属性.

It is getting each label which has all the text properties that you can set for it.

这篇关于使用 Matplot Lib 将字体属性设置为刻度标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆