Python matplotlib绘图设置图例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python matplotlib绘图设置图例

返回主页悬崖上的金鱼   2022-05-23 我要评论

一、语法简介

plt.legend(loc=2,edgecolor='red',facecolor='green',shadow='True',fontsize=10)

  • edgecolor 图例边框线颜色
  •  facecolor 图例背景色
  • shadow 是否添加阴影
  •  title 图例标题
  • fontsize 设置字体大小

'''
设置图例位置loc参数简介
best         0  根据图标区域自动选择最合适的位置
upper right  1  右上角
upper left   2  左上角
lower left   3  左下角
lower right  4  右下角
right        5  右侧
center left  6  左侧中心
center right 7  右侧中心
lower center 8  底部中心
upper center 9  顶部中心
center       10 正中心位置
'''

二、完整代码

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,label='销售数量') #绘制柱状图

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.xlim(-1,9) #设置x轴刻度值的范围
plt.ylim(0,900)#设置y轴刻度值的范围
plt.axis("on")
#plt.axis("off") #关闭坐标轴

plt.legend(loc=2,edgecolor='red',facecolor='green',shadow='True',fontsize=10)
#edgecolor 图例边框线颜色 facecolor 图例背景色 shadow 是否添加阴影 title 图例标题 fontsize 设置字体大小
'''
设置图例位置loc参数简介
best         0  根据图标区域自动选择最合适的位置
upper right  1  右上角
upper left   2  左上角
lower left   3  左下角
lower right  4  右下角
right        5  右侧
center left  6  左侧中心
center right 7  右侧中心
lower center 8  底部中心
upper center 9  顶部中心
center       10 正中心位置
'''
plt.show()

三、效果图展示


Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们