如题
我在用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轴输出的是对应的日期。
然后我们把这两个定义的方法分别传入yaxis
和xaxis
对应的方法中。
plt.gca().yaxis.set_major_formatter(FuncFormatter(y_update_scale_value))
plt.gca().xaxis.set_major_formatter(FuncFormatter(x_update_scale_value))
新的结果如下图所示
看着是不是舒服点的呢,当然数值更大,你可以返回万、亿等等。总之是一个不错的方法。