matplotlib小记(一)——等比例缩放x轴y轴

在平常使用python绘图的过程当中,常常会遇到须要按比例缩放x、y轴的状况。
好比我当前的数据是按照每15分钟一个点来采集与统计的,所以一天以内会有96个数据点,横坐标也是按照1~96来区分,那么为了更好的体现某一时刻的数据,但愿横坐标以小时为单位,即原坐标为4的,即为1点,为8的为2点。
为了模拟这种情形,我能够先按照下面的代码,随机出以下的图像:python

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FuncFormatter

x = np.arange(1, 96, 1)
y = [-0.8*i*i*i+68*i*i + 196*i + 44 for i in x]
plt.scatter(x, y)
plt.show()

这里写图片描述

此时,你能够经过从新设计一个大小为96的列表,存放对应的x的值,更通常且方便的,能够采用以下形式来实现:web

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import FuncFormatter

def changex(temp, position):
    return int(temp/4)

def changey(temp, position):
    return int(temp/100)

x = np.arange(1, 96, 1)
y = [-0.8*i*i*i+68*i*i + 196*i + 44 for i in x]
plt.gca().xaxis.set_major_formatter(FuncFormatter(changex))
plt.gca().yaxis.set_major_formatter(FuncFormatter(changey))
plt.scatter(x, y)
plt.show()

这就实现了对x和y轴的等比例缩放,须要导入FuncFormatter这一库,以后自定义你须要缩放的比例,并经过gca函数套用自定义的比例便可,最终的效果图以下:
这里写图片描述
x轴均缩小了4倍,而y轴缩小了10倍,与我定义的函数体至关。svg