gpt4 book ai didi

python - 更改 Matplotlib 字体而不影响全局

转载 作者:太空宇宙 更新时间:2023-11-03 17:15:16 25 4
gpt4 key购买 nike

我有一个函数可以创建绘图、显示它并保存它:

def make_a_plot():
plt.plot(x,y)
plt.show()
plt.safefig('./my_plot.png')

我希望绘图不受当前任何设置的影响,而不进行影响他们正在使用的设置的全局更改:

# User can set whatever plotting settings they want
plt.style.use('ggplot')

def make_a_plot():

#clear settings and modify font family
rcdefaults()
rcParams['font.family'] = 'sans-serif'

plt.plot(x,y)
plt.show()
plt.safefig('./my_plot.png')

# Use the function
make_a_plot(x,y)

# Create a second plot with their ORIGINAL settings
plt.plot(x2,y2)
plt.show()

如何确保该函数创建的绘图不会受到用户设置的影响,并且在该函数之后创建的绘图不会受到该函数使用的影响?

最佳答案

您的问题的范围有些不清楚。

您是否想要(仅)控制/覆盖字体属性,而不管全局设置如何,还是您想要忽略所有现有设置。

如果您只想控制字体属性,则可以使用 fontproperties 参数:

import matplotlib.pyplot as plt
import matplotlib.font_manager as fm

# Plt with customized font settings
def make_plot(ax, x, y):
# Set the font dictionaries (for plot title and axis titles)
title_font = {'fontname':'Arial', 'size':'16', 'color':'blue', 'weight':'normal'} # This can be a long dictionary

# Set the font properties for other places
font_path = 'C:\Windows\Fonts\comic.ttf'
font = fm.FontProperties(fname=font_path, size=14)
axis_font = fm.FontProperties(fname=font_path, size=13)

# Set the tick labels font
for label in (ax.get_xticklabels() + ax.get_yticklabels()):
# label.set_fontname('Arial')
# label.set_fontsize(13)
label.set_font_properties(font)

ax.plot(x, y, 'r-', label=u'Thin Red Line')
ax.set_xlabel(u"X axis", fontproperties=axis_font)
ax.set_ylabel(u"Y axis", fontproperties=axis_font)
ax.set_title(u"This is the Title", **title_font)
ax.legend(loc='lower right', prop=font, numpoints=1)
ax.text(0.1, 5, u"Some text", fontproperties=font)

# A regular plot with global fong settings:
def regular_plot(ax, x, y):
ax.plot(x,y, 'b-', label=u'Blue Line')
ax.set_xlabel(u"X axis")
ax.set_ylabel(u"Y axis")
ax.set_title(u"This is the Title", axes=ax1)
ax.legend(loc='lower right', numpoints=1)

fig, (ax1, ax2, ax3) = plt.subplots(1,3, figsize=(9,3))
x = y = range(0, 10) # Some data

# 1st make a regular plot:
regular_plot(ax1, x, y)
# then make customized plot:
make_plot(ax2, x, y)
# then agains a regular plot:
regular_plot(ax3, x, y)
plt.show()

从结果图中可以看出,自定义绘图没有改变,也不受全局字体设置的影响。

enter image description here

如果您正在寻找更完整的控件,您可能需要了解如何使用 style sheets

关于python - 更改 Matplotlib 字体而不影响全局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33712461/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com