Seaborn/MatplotLib轴和数据值格式:数百、数千和数百万

2024-10-01 19:20:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有个问题,据我所知还没有解决。你知道吗

我需要格式化我的轴和数据点为我的Seaborn/Matplotlib图是动态的。下面是我想要实现的一个例子(通过Keynote完成,我使用了一个对数比例来更清楚地说明这一点)。你知道吗

最好的办法是什么?我看到答案的格式要么是Ks要么是Ms,但从来没有两者都是。我错过什么了吗?你知道吗

enter image description here

现在我正在使用FuncFormatter选项

if options.get('ctype') == 'number':

    df = df.loc[df[ycat2] >= 1].copy()
    plt.figure(figsize=(14,7.5))
    plot = sns.barplot(xcat1, ycat2, data=df, color='#00c6ff', saturation=1, ci=None)

    sns.despine(top = True, right = True, left=True)
    #plot.set_title('Instagram - Engagement Rate', fontweight='bold',y=1.04, loc = 'left', fontsize=12)

    plot.yaxis.grid(True)
    plot.yaxis.get_major_ticks()[0].label1.set_visible(False)
    plot.yaxis.set_major_formatter(FuncFormatter(lambda y, _: '{:,}'.format(int(y))))
    plot.set_xlabel('')
    plot.set_ylabel('')
    plot.tick_params(axis="x", labelsize=13)
    plot.tick_params(axis="y", labelsize=13)

    for i, bar in enumerate(plot.patches):

        h = bar.get_height()

        plot.text(
            i, 
            h,
            '{:,}'.format(int(h)),
            ha='center', 
            va='bottom',
            fontweight='heavy',
            fontsize=12.5)


    return plot.figure

Tags: truedfgetplotleftlocfigureset
1条回答
网友
1楼 · 发布于 2024-10-01 19:20:25

Matplotlib有一个Engineering formatter专门用于此目的。您可以使用它格式化轴(使用set_major_formatter())或格式化任何数字,使用^{}

from matplotlib.ticker import EngFormatter
fmt = EngFormatter(places=0)

y = np.arange(1,10)
data = np.exp(3*y)
fig, ax = plt.subplots()
ax.set_xscale('log')
bars = ax.barh(y=y, width=data)
ax.xaxis.set_major_formatter(fmt)

for b in bars:
    w = b.get_width()
    ax.text(w, b.get_y()+0.5*b.get_height(),
            fmt.format_eng(w),
            ha='left', va='center')

enter image description here

相关问题 更多 >

    热门问题