day04-matplotlib入门

发布于:2024-07-06 ⋅ 阅读:(42) ⋅ 点赞:(0)

matplotlib

在这里插入图片描述
在这里插入图片描述

Matplotlib 提供了一个套面向绘图对象编程的 API接口

是一款用于数据可视化的 Python 软件包,支持跨平台运行

它能够根据 NumPyndarray 数组来绘制 2D(3D) 图像,它使用简单、代码清晰易懂,深受广大技术爱好 者喜爱。

实列:绘制x轴为-50-50,y轴为x轴的平方的直方图

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(-50,51)
y = x ** 2

plt.plot(x,y)

在这里插入图片描述

一、matplotlib的基本方法

方法名 说明
title() 设置图表的名称
xlabel() 设置x轴名称
ylabel() 设置y轴名称
xticks(ticks,label,rotation) 设置x轴的刻度,rotation旋转角度
yticks() 设置y轴的刻度
show() 显示图表
legend() 显示图例
text(x,y,text) 显示每条数据的值 x,y值的位置
1. 图表名称 plt.title()
plt.title("y= x^2的图表")
plt.plot(x,y)
  • 参数fontsize:设置标题的字体大小

在这里插入图片描述

默认不支持中文:missing from current font 字体丢失

需要设置字体:

plt.rcParams["font.sans-serif"] = ["下列中文字体名称"]
#如
plt.rcParams['font.sans-serif'] = ["FangSong"]
plt.rcParams['font.sans-serif'] = ["SimHei"]
中文字体 说明
‘SimHei’ 中文黑体
‘Kaiti’ 中文楷体
‘LiSu’ 中文隶书
‘FangSong’ 中文仿宋
‘YouYuan’ 中文幼圆
STSong 华文宋体

但出现了新的问题,负号识别不了,因此还需要设置

不适用unicode的负号 axis的复数-axes,表示所有坐标轴

plt.rcParams['axes.unicode_minus'] = False

完整的运行一遍

import matplotlib.pyplot as plt
# 引入numpy包
import numpy as np


# 获得-50到50之间的ndarray对象
x = np.arange(-50,51)
plt.title("y等于x的平方")
plt.rcParams['font.sans-serif'] = ["FangSong"]
# 用来设置字体样式以正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False
# 默认是使用Unicode负号,设置正常显示字符,如正
plt.plot(x,y)

在这里插入图片描述

2.x轴和y轴名称

注意,只对下一次绘画有作用

xlable("x轴名称")
ylable("y轴名称")
# 设置x轴名称
plt.xlabel("x 轴",fontsize = 18)
# 设置y轴名称
plt.ylabel("y 轴",fontsize = 20)

plt.plot(x,y)

参数:

  • fontsize:设置字体大小

在这里插入图片描述

3.设置线条粗细

plt.plot(x,y,linewidth = 5)

在这里插入图片描述

绘制两条线段

# 创建x为-10到10的整数
x = np.arange(-10,10)
# y是x的平方
y1 = x ** 2
y2 = x ** 1
# 设置标题
plt.title('坐标系',fontsize=16)
# 设置x轴名称 ,值不能写"12px"
plt.xlabel("x 轴",fontsize=12)
# 设置y轴名称
plt.ylabel("y 轴")
plt.plot(x, y1,linewidth=5)
plt.plot(x, y2,linewidth=1)

在这里插入图片描述

4. 设置x轴和y轴的刻度

matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs)
matplotlib.pyplot.yticks(ticks=None, labels=None, **kwargs)
  • ticks: 此参数是xtick位置的列表。和一个可选参数。如果将一个空列表作为参数传递,则它将删除所有xticks
  • label: 此参数包含放置在给定刻度线位置的标签。它是一个可选参数。,
  • **kwargs:此参数是文本属性,用于控制标签的外观
    • rotation:旋转角度 如:rotation=45
    • color:颜色 如:color=“red”

xticks到底有什么用,其实就是想把坐标轴变成自己想要的样子

对于数值型的x轴或y轴,可以给ticks传一个数值列表,

对于字符型的x轴或y轴数据,可以给ticks传一个序号列表

times = ['2015/6/26', '2015/8/1', '2015/9/6', '2015/10/12', '2015/11/17','2015/12/23','2016/1/28','2016/3/4','2016/4/9',
'2016/5/15','2016/6/20','2016/7/26','2016/8/31','2016/10/6','2016/11/11','2016/12/17']

# 随机出销量
sales =np.random.randint(500,2000,size=len(times))

# 绘制图形
plt.plot(times,sales)

作图后,其x轴会全部显示,显得杂乱,就需要ticks剔除部分

在这里插入图片描述

# 如果想只显示部分时间,或者按照某个规则展示,如何处理,这个时候就用到xticks
plt.xticks(range(0,len(times),3))#每隔3个显示x轴信息。
plt.plot(times,sales)

在这里插入图片描述

plt.xticks(range(0,len(times),3),rotation = 45,color = 'red')#每隔3个显示x轴信息。且将x轴信息旋转45度角,显示为红色
plt.plot(times,sales)

在这里插入图片描述

想要将x轴的信息自定义,则使用labels参数

plt.xticks(range(0,len(times),2),labels= range(1,9))
#labels元素不够时,将为空,不显示
plt.plot(times,sales)

在这里插入图片描述

还可以单独使用并按照想要的格式

x_titcks  =range(0,15,2)
x_labels = ['%s月'%i for i in x_titcks]
plt.xticks(x_titcks,x_labels)
plt.plot(times,sales)

在这里插入图片描述

  • 注意,当x轴数据不是str_类型,它可以自动无遮挡显示
times = range(10,50)
sales =np.random.randint(500,2000,size=len(times))

plt.plot(times,sales)

在这里插入图片描述

times = range(10,100)
sales =np.random.randint(500,2000,size=len(times))


plt.plot(times,sales)

在这里插入图片描述

当x轴时str_类型时,则会全部显示

times = np.arange(10,50).astype(np.str_)
sales =np.random.randint(500,2000,size=len(times))

plt.plot(times,sales)

外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传

一般使用下列语句减少显示数量

plt.xticks(range(0,len(times),2))

在这里插入图片描述

4.显示图表show()

  • 显示所有打开的图形。

jupyter notebooks会自动显示图形

而一般的python交互模式需要

# 如果在jupyter中也想出现图形操作菜单,可以使用matplotlib中的魔术方法
%matplotlib notebook

# 如果有想回去原先的展示,使用另一个 %matplotlib inline
%matplotlib inline

5.图例 legend()

图例是集中于地图一角或一侧的地图上各种符号和颜色所代表内容与指标的说明,有助于更好的认识地图。

在这里插入图片描述

# 每个时间点的销量绘图
times = ['2015/6/26', '2015/8/1', '2015/9/6', '2015/10/12']

# 随机出收入
income =np.random.randint(500,2000,size=len(times))
# 支出
expenses =np.random.randint(300,1500,size=len(times))

# 绘制图形
# 注意,在使用图例前为每个图形设置label参数
plt.plot(times,income,label="收入")
plt.plot(times,expenses,label="支出")
# 默认会使用每个图形的label值作为图例中的说明
plt.legend()

在这里插入图片描述

5.1图例的图例位置设置

  • loc代表了图例在整个坐标轴平面中的位置(一般选取’best’这个参数值)
    • 第一种:默认是"best",图例自动‘安家’在一个坐标面内的数据图表最少的位置
    • 第二种: loc = ‘XXX’ 分别有0: ‘best’ (自动寻找最好的位置)
位置字符串 位置值 备注
“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.legend(loc = 'center')

6.显示每条数据的值 x,y值的位置

plt.text(x,y,  string,  fontsize=15,  verticalalignment="top",  horizontalalignment="right")
  • x,y:表示坐标值上的值
  • string:表示说明文字
  • fontsize:表示字体大小
  • verticalalignment:(va)垂直对齐方式 ,参数:[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
  • horizontalalignment:(ha)水平对齐方式 ,参数:[ ‘center’ | ‘right’ | ‘left’ ]

plt.text()一次只能描绘一个点的信息

因此需要使用循环

for x,y in zip(times,income):
    plt.text(x,y,'%s万'%y)
    
for a,b in zip(times,expenses):
    plt.text(a,b,b)

在这里插入图片描述

总结:

  • x轴是数值型,会按照数值型本身作为x轴的坐标
  • x轴为字符串类型,会按照索引作为x轴的坐标

labels的注意点:

time=np.arange(2000,2020).astype(np.str_)
sales = [109, 150, 172, 260, 273, 333, 347, 393, 402, 446, 466, 481, 499,504, 513, 563, 815, 900, 930, 961]
plt.xticks(range(0,len(time),2),labels=['year%s'%i for i in time],rotation=45,color="red")
#plt.xticks(range(0,len(time),2),labels=['year%s'%time[i] for i in range(0,len(time),2)],rotation=45,color="red")
plt.yticks(color="blue")
plt.plot(time,sales)

网站公告

今日签到

点亮在社区的每一天
去签到