首页 文章

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

提问于
浏览
0

我试图在不同类型的推文('普通'推文,转发和回复)中绘制表情符号的使用频率。为了这个目的,我使用 TwitterColorEmoji-SVGinOT(链接)字体来渲染表情符号的 Unicode,我把它作为 xticks 标签用plt.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()

结果

先感谢您。

解决方案感谢@cheersmate,@ ImportanceOfBeingErnest 提供了有用的建议。实际上,使用函数**ax.set_xticks()ax.set_xticklabels()**我可以获得所需的结果。

这是更新的方法:

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')

    ax.set_xticks(x_pos)
    ax.set_xticklabels(emojis, fontproperties=fontprop)

    ax.set_xticks(x_pos)

    ax.set_ylabel('Popularity Score')

这是最后的结果

结果 2

1 回答

  • 0

    正如 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])
    

    在此输入图像描述

相关问题