【划重点】Python matplotlib绘图设置坐标轴的刻度


一、语法简介

plt.xticks(ticks,labels,rotation=30,fontsize=10,color='red',fontweight='bold',backgroundcolor='black') 
#ticks 表示刻度值 labels表示该该刻度值对应的标签 rotation设置刻度值倾斜角度
fontsize设置字体大小,color设置字的颜色,fontweight设置标签是否加粗 backgroundcolor设置背景颜色
plt.yticks(ticks,labels) 

  plt.xticks(x,['2021年1月','2021年2月','2021年3月','2021年4月','2021年5月','2021年6月','2021年7月','2021年8月',],rotation=15)
  plt.yticks(y,['100k','200k','300k','400k','500k','600k','700k','800k',],
  rotation=30,fontsize=10,color='red',fontweight='bold',backgroundcolor='black')#rotation设置刻度值倾斜角度

二、对应完整代码如下所示

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams['font.sans-serif'] = ['STZhongsong'] # 指定默认字体:解决plot不能显示中文问题
plt.rcParams['axes.unicode_minus'] = False #用来正常显示负号

x=np.arange(8)
y=np.arange(100,900,100)

print(y)
#建立画布 figsize,它用width和height来控制画布的宽和高
plt.figure(figsize=(8,6),dpi=90) #facecolor='red'设置画布颜色

plt.subplot(1,1,1)#建立坐标系
plt.bar(x,y) #绘制柱状图

plt.xlabel("销售月份",fontsize=10,color='red',fontweight='bold',loc='center',backgroundcolor='black',labelpad=6)
#显示横坐标标题 fontsize设置字体大小,color设置字的颜色,fontweight设置标签是否加粗
#loc设置标签位置(具体值有center left right) backgroundcolor设置标签的背景颜色 labelpad与轴的距离
plt.ylabel("销售数量")

plt.xticks(x,['2021年1月','2021年2月','2021年3月','2021年4月','2021年5月','2021年6月','2021年7月','2021年8月',],rotation=15)
plt.yticks(y,['100k','200k','300k','400k','500k','600k','700k','800k',],
rotation=30,fontsize=10,color='red',fontweight='bold',backgroundcolor='black')#rotation设置刻度值倾斜角度


plt.show()

三、对应效果图如下所示