python刻度
⑴ 用python设置matplotlib.plot的坐标轴刻度间隔以及刻度范围
转自 跳转链接
一、用默认设置绘制折线图
import matplotlib.pyplot as plt
x_values=list(range(11))
#x轴的数字是0到10这11个整数
y_values=[x**2 for x in x_values]
#y轴的数字是x轴数字的平方
plt.plot(x_values,y_values,c='green')
#用plot函数绘制折线图,线条颜色设置为绿色
plt.title('Squares',fontsize=24)
#设置图表标题和标题字号
plt.tick_params(axis='both',which='major',labelsize=14)
#设置刻度的字号
plt.xlabel('Numbers',fontsize=14)
#设置x轴标签及其字号
plt.ylabel('Squares',fontsize=14)
#设置y轴标签及其字号
plt.show()
#显示图表
制作出图表
我们希望x轴的刻度是0,1,2,3,4……,y轴的刻度是0,10,20,30……,并且希望两个坐标轴的范围都能再大一点,所以我们需要手动设置。
二、手动设置坐标轴刻度间隔以及刻度范围
import matplotlib.pyplot as plt
from matplotlib.pyplot import MultipleLocator
#从pyplot导入MultipleLocator类,这个类用于设置刻度间隔
x_values=list(range(11))
y_values=[x**2 for x in x_values]
plt.plot(x_values,y_values,c='green')
plt.title('Squares',fontsize=24)
plt.tick_params(axis='both',which='major',labelsize=14)
plt.xlabel('Numbers',fontsize=14)
plt.ylabel('Squares',fontsize=14)
x_major_locator=MultipleLocator(1)
#把x轴的刻度间隔设置为1,并存在变量里
y_major_locator=MultipleLocator(10)
#把y轴的刻度间隔设置为10,并存在变量里
ax=plt.gca()
#ax为两条坐标轴的实例
ax.xaxis.set_major_locator(x_major_locator)
#把x轴的主刻度设置为1的倍数
ax.yaxis.set_major_locator(y_major_locator)
#把y轴的主刻度设置为10的倍数
plt.xlim(-0.5,11)
#把x轴的刻度范围设置为-0.5到11,因为0.5不满一个刻度间隔,所以数字不会显示出来,但是能看到一点空白
plt.ylim(-5,110)
#把y轴的刻度范围设置为-5到110,同理,-5不会标出来,但是能看到一点空白
plt.show()
绘制结果
⑵ python中怎么让图所有坐标轴都有刻度
plt.tick_params(top='on', right='on', which='both') # 显示上侧和右侧的刻度
plt.rcParams['xtick.direction'] = 'in' #将x轴的刻度线方向设置向内
plt.rcParams['ytick.direction'] = 'in' #将y轴的刻度方向设置向内
(PS:如果第一次运行上面的两个命令坐标轴没有朝内的话,关闭图像,再运行一次就可以达到效果了。)
⑶ python matplotlib 绘制带有刻度的箭头
#绘制箭头例子
def arrow():
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.style.use('seaborn-deep')
fig = plt.figure(figsize=(16, 9),dpi=75)
ax = fig.add_subplot(121)
x=np.array([1,2,3,4])
y=np.array([2,4,6,8])
ax.plot(x,y,color = 'b')
ax.annotate("",
xy=(4.5, 9),
xytext=(4, 8),
arrowprops=dict(arrowstyle="->", color="r"))
# 设置X轴、Y轴最大坐标
ax.set_xlim(0, 10)
ax.set_ylim(0, 10)
ax.grid()
ax.set_aspect('equal')
plt.title("趋势展示图")
plt.show()
arrow()