You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在plotnine中格式化x、y坐标的小数位数

如何修改plotnine图表右下角坐标的小数位数?

你可以通过修改底层matplotlib的坐标轴格式器实现需求,因为plotnine基于matplotlib开发。以下是修改后的完整代码:

from plotnine import ggplot, aes, geom_line
import pandas as pd
from matplotlib.ticker import FormatStrFormatter
import matplotlib.pyplot as plt

df = pd.DataFrame([[1,1], [2,4], [3,9], [4,16], [5,25]], columns=['x', 'y'])
print(df)

g = (
    ggplot(df)
    + aes(x="x", y="y")
    + geom_line()
)

# 获取matplotlib图表对象并设置坐标格式
fig = g.draw()
for ax in fig.get_axes():
    # 设置x、y轴坐标显示为4位小数
    ax.xaxis.set_major_formatter(FormatStrFormatter('%.4f'))
    ax.yaxis.set_major_formatter(FormatStrFormatter('%.4f'))

plt.show()

关键说明:

  • 导入FormatStrFormatter定义坐标显示格式,'%.4f'表示保留4位小数,可根据需求调整位数(比如'%.2f'保留2位)。
  • 通过g.draw()将plotnine的ggplot对象转换为matplotlib的figure对象,再获取所有坐标轴进行格式设置。
  • 也可以用lambda函数自定义格式,替换上述格式器设置:
    ax.xaxis.set_major_formatter(lambda x, pos: f"{x:.4f}")
    ax.yaxis.set_major_formatter(lambda x, pos: f"{x:.4f}")
    

内容的提问来源于stack exchange,提问作者rth

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 13:23:11