【问题标题】:How to set xticks and font properties of pyplot subplots?如何设置 pyplot 子图的 xticks 和字体属性?
【发布时间】:2019-05-13 08:18:36
【问题描述】:

我正在尝试绘制表情符号在不同类型的推文(“正常”推文、转发和回复)中的使用频率。 为此,我使用 TwitterColorEmoji-SVGinOT (link) 字体来呈现我使用 plt.xticks() 作为 xticks 标签放置的表情符号的 Unicode。 但是,它只正确设置了最后一个子图的 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()

【问题讨论】:

  • 你试过用 ax.set_xticks 替换 plt.xticks 吗?
  • plt.xticks 适用于当前活动的轴,这是最后一个创建的轴。而是使用实际的轴,ax.set_xticksax.set_xticklabels

标签: python matplotlib subplot


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-22
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    相关资源
    最近更新 更多