matplotlib如何自定义坐标轴的数值单位

如题

我在用tableau转到matplotlib中作图时,感觉不是很智能。尤其是y坐标轴的值,不能自动的进行转换。这样就显得很呆。
在这里插入图片描述
这样就显得y轴上的坐标值很大,看着很不舒服。

解决方法:

from matplotlib.ticker import FuncFormatter
plt.gca().yaxis.set_major_formatter(FuncFormatter(y_update_scale_value))
plt.gca().xaxis.set_major_formatter(FuncFormatter(x_update_scale_value))

引入一个类,类中需要传一个函数,返回值为坐标新展示的值。
点进去这个类看一下。

"""
    Use a user-defined function for formatting.

    The function should take in two inputs (a tick value ``x`` and a
    position ``pos``), and return a string containing the corresponding
    tick label.
    """
    def __init__(self, func):
        self.func = func

这是说明意思就是你需要传一个方法,这个方法必须包含两个参数,tick_value 和 position。这两个参数分别为坐标轴上值和该值对应的位置。这时候我们只需定义相关的方法即可。

def y_update_scale_value(temp, position):
    result = temp//1000
    return "{}k".format(int(result))


def x_update_scale_value(temp, position):
    return "{}d".format(int(temp))

我的y轴定义的方法为,把该值整除1000然后把结果加个一个k,输出。
x轴的定义的方法为,把该值加上d传出,这样会严谨一些。代表我们x轴输出的是对应的日期。
然后我们把这两个定义的方法分别传入yaxisxaxis对应的方法中。

plt.gca().yaxis.set_major_formatter(FuncFormatter(y_update_scale_value))
plt.gca().xaxis.set_major_formatter(FuncFormatter(x_update_scale_value))

新的结果如下图所示
在这里插入图片描述
看着是不是舒服点的呢,当然数值更大,你可以返回万、亿等等。总之是一个不错的方法。

  • 10
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值