如何设置 pyplot 子图的 xticks 和字体属性?

How to set xticks and font properties of pyplot subplots?

我正在尝试绘制表情符号在不同类型推文('normal' 推文、转推和回复)中的使用频率。 为此,我使用 TwitterColorEmoji-SVGinOT (link) 字体来呈现表情符号的 Unicode,我用 plt.xticks() 作为 xticks 标签. 但是,它仅正确设置了最后一个子图的 xticks(见下图)。

如何对所有子图执行相同的操作?

这是我用来制作绘图的代码。

import matplotlib.font_manager as fm
from matplotlib import ft2font
from matplotlib.font_manager import ttfFontProperty

def print_emoji_freq(emoji_freqs, ax, fontprop):

    emojis = list(zip(*emoji_freqs))[0]
    scores = list(zip(*emoji_freqs))[1]
    x_pos = np.arange(len(emojis))

    ax.bar(x_pos, scores, align='center')
    plt.xticks(x_pos, emojis, fontproperties=fontprop)

    ax.set_xticks(x_pos)
    ax.set_ylabel('Popularity Score')

fpath = '/home/mattia/.local/share/fonts/TwitterColorEmoji-SVGinOT.ttf'
fprop = fm.FontProperties(fname=fpath)

font = ft2font.FT2Font(fpath)
fprop = fm.FontProperties(fname=fpath)

ttfFontProp = ttfFontProperty(font)

fontprop = fm.FontProperties(family='sans-serif',
                            fname=ttfFontProp.fname,
                            size=25,
                            stretch=ttfFontProp.stretch,
                            style=ttfFontProp.style,
                            variant=ttfFontProp.variant,
                            weight=ttfFontProp.weight)

fig, ax = plt.subplots(1, 3, figsize=(18,4))

print_emoji_freq(st_emojis, ax[0], fontprop)
print_emoji_freq(rt_emojis, ax[1], fontprop)
print_emoji_freq(rp_emojis, ax[2], fontprop)

plt.show()

正如 ImportanceOfBeingErnest 所建议的,您不能使用 plt.xticks(),因为它们适用于当前轴 (plt.gca())。您需要为此使用 ax 对象:

from matplotlib.font_manager import FontProperties
import matplotlib.pyplot as plt

def plot_function(ax):
    fm = FontProperties(weight='bold')
    ax.set_xticks([1, 3, 5])
    ax.set_xticklabels(['one', 'three', 'five'], fontproperties=fm)

fig, ax = plt.subplots(1, 3)

plot_function(ax[0])
plot_function(ax[1])
plot_function(ax[2])