1.Matplotlib简介
Matplotlib是一个Python的2D绘图库,它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形。通过Matplotlib,开发者可以仅需要几行代码,便可以生成绘图,折线图、散点图、柱状图、饼图、直方图、子图等。Matplotlib使用NumPy进行数组运算,并调用一系列其他的Python库来实现硬件交互。
2.主要方法介绍
- plt.plot(x,y,format_string,**kwargs)
x---x轴的数据;y---y轴的数据;format_string---表示画出的图中,数据点以及线的属性(形状,大小,颜色等)
颜色字符 | 说明 | 颜色字符 | 说明 |
---|---|---|---|
'b' | blue | 'm' | magenta洋红色 |
'g' | green | 'y' | 黄色 |
'r' | red | 'k' | 黑色 |
'c' | cyan青绿色 | 'w' | 白色 |
'#008000' | RGB某颜色 | '0.8' | 灰度值字符串 |
风格字符 | 说明 |
---|---|
'-' | 实线 |
'--' | 破折线 |
'-.' | 点划线 |
':' | 虚线 |
' ' | 无线条 |
标记字符 | 说明 | 标记字符 | 说明 | 标记字符 | 说明 |
---|---|---|---|---|---|
'.' | 点标记 | '1' | 下花三角标记 | 'h' | 竖六边形标记 |
',' | 像素标记(极小点) | '2' | 上花三角标记 | 'H' | 横六边形标记 |
'o' | 实心圏标记 | '3' | 左花三角标记 | '+' | 十字形标记 |
'v' | 倒三角标记 | '4' | 右花三角标记 | 'x' | x标记 |
'^' | 上三角标记 | 's' | 实心方形标记 | 'D' | 菱形标记 |
'>' | 右三角标记 | 'p' | 实心五角标记 | 'd' | 瘦菱形标记 |
'<' | 左三角标记 | '*' | 星形标记 | ' | ' |
其中,这些属性可以任意组合。比如:'r--' 表示红色破折现
- figure(figsize=(x,y),dpi=m)----表示所画的图大小为x*y,分辨率为m
- xlabel()&&ylabel()----可以传递参数,表示x/y轴的标签说明
- axis([x1,x2,y1,y2])----表示坐标轴的范围,即x轴从x1到x2,y轴从y1到y2
- savefig(x,y)----用来存储图片,x表示图片文件名,y可以表示存储图片的分辨率
- subplot()----在全局绘制区域中创建一个分区体系,并定位到一个子绘图区域。用来画多个图,若参数为211,表示画一个2行1列的图(上下各一幅图),目前操作第一幅图。按照从左到右,从上到下对子图进行编号
- grid()----表示再图中显示网格
- title()----整张图的标题
- legend()----对图中的每条曲线做出区分,就是指出哪条曲线对应什么函数---------具体说明
- show()----显示图
- scatter(x,y)----画散点图,x,y分别表示数据
import matplotlib.pyplot as plt
import numpy as np
#准备数据
x = np.array([1,2,3,4,5,6])
y1 = x*2+5
y2 = np.sin(x)
plt.axis([0,10,6,20])
plt.subplot(121)
plt.title("示例1")
plt.xlabel("x轴数据")
plt.ylabel("y1")
plt.plot(x,y1,'b--')
plt.legend(['y1'],loc="upper right")
plt.subplot(1,2,2)
plt.title("示例2")
plt.xlabel("x轴数据")
plt.ylabel("y2")
plt.plot(x,y2,'r--D')
plt.grid()
plt.legend(['y2'],loc="upper right")
plt.show()
这里存在一个问题:标题以及坐标轴说明文字中的中文无法显示,怎么办呢????
方案一:
要导包
import matplotlib
matplotlib.rcParams['font.family']='SimHei'
但是这样设置是全局,就是图中出现的中文都是这样的格式。不够灵活。
方案二:
在需要输出中文的地方设置属性
plt.xlabel("x轴数据",fontproperties='SimHei',fontsize=20)
中文博大精深,下面看看可以设置什么格式的中文;
属性 | 说明 |
---|---|
'font.family' | 用于显示字体的名字 |
'font.style' | 字体风格,正常'normal'或斜体'italic' |
'font.size' | 字体大小,整数字号或者'large','x-small' |
字体选项;
'SimHei' ----中文黑体 'Kaiti' ---- 中文楷体 'LiSu' ----中文隶书 'FangSong' ----中文仿宋
'YouYuan' ----中文幼圆 'STSong'---- 华文宋体
- bar()----画柱状图
x = np.arange(10)
y = np.random.randint(0,30,10)
plt.bar(x,y)
plt.show()
matplotlib.pyplot.bar(x, width, align='center', **kwargs)方法说明:
Parameters:
x : sequence of scalars.
width : scalar or array-like, optional
柱状图的宽度
align : {‘center’, ‘edge’}, optional, default: ‘center’
Alignment of the bars to the x coordinates:
‘center’: Center the base on the x positions.
‘edge’: Align the left edges of the bars with the x positions.
每个柱状图的位置对齐方式
**kwargs :
color:选择柱状图的颜色
Returns:
`.BarContainer`
Container with all the bars and optionally errorbars.
- pie()----画饼图
labels = ['变量1','变量2','变量3','变量4','变量5']
sizes = [10,16,17,62,53]
colors = ['red','yellow','blue','pink','green']
explode= [0,0.2,0,0,0]
plt.pie(sizes,explode=explode,labels=labels,colors=colors,autopct='%1.2f%%',shadow=True,startangle=50)
plt.axis('equal')
plt.show()
pie()方法说明:
labels:图中各部分对应的描述
size:图中各部分对应的数量
colors:想要图中各部分呈现的颜色
explode:参数为0表示不分裂,大于0表示往外分裂(值越大分裂程度越大),小于0往内分类(无意义)
autopct:图中各部分显示的比例格式
shadow:是否需要阴影效果
startangle:开始的角度
- hist()----画直方图
介绍:直方图,形状类似柱状图却有着与柱状图完全不同的含义。直方图牵涉统计学的概念,首先要对数据进行分组,然后统计每个分组内数据元的数量。 在坐标系中,横轴标出每个组的端点,纵轴表示频数,每个矩形的高代表对应的频数,称这样的统计图为频数分布直方图。
组数:在统计数据时,我们把数据按照不同的范围分成几个组,分成的组的个数称为组数
组距:每一组两个端点的差
柱状图是以矩形的长度表示每一组的频数或数量,其宽度(表示类别)则是固定的,利于较小的数据集分析。
直方图是以矩形的长度表示每一组的频数或数量,宽度则表示各组的组距,因此其高度与宽度均有意义,利于展示大量数据集的统计结果。
由于分组数据具有连续性,直方图的各矩形通常是连续排列,而柱状图则是分开排列。
time = [131, 98, 125, 131, 124, 139, 131, 117, 128, 108, 135, 138, 131, 102, 107, 114, 119,
128, 121, 142, 127, 130, 124, 101, 110, 116, 117, 110, 128, 128, 115, 99, 136, 126,
134, 95, 138, 117, 111,78, 132, 124, 113, 150, 110, 117, 86, 95, 144, 105, 126, 130,
126, 130, 126, 116, 123, 106, 112, 138, 123, 86, 101, 99, 136,123, 117, 119, 105, 137,
123, 128, 125, 104, 109, 134, 125, 127,105, 120, 107, 129, 116, 108, 132, 103, 136, 118,
102, 120, 114,105, 115, 132, 145, 119, 121, 112, 139, 125, 138, 109, 132, 134,156, 106,
117, 127, 144, 139, 139, 119, 140, 83, 110, 102,123,107, 143, 115, 136, 118, 139, 123,
112, 118, 125, 109, 119, 133,112, 114, 122, 109, 106, 123, 116, 131, 127, 115, 118, 112,
135,115, 146, 137, 116, 103, 144, 83, 123, 111, 110, 111, 100, 154,136, 100, 118, 119,
133, 134, 106, 129, 126, 110, 111, 109, 141,120, 117, 106, 149, 122, 122, 110, 118, 127,
121, 114, 125, 126,114, 140, 103, 130, 141, 117, 106, 114, 121, 114, 133, 137, 92,121,
112, 146, 97, 137, 105, 98, 117, 112, 81, 97, 139, 113,134, 106, 144, 110, 137, 137,
111, 104, 117, 100, 111, 101, 110,105, 129, 137, 112, 120, 113, 133, 112, 83, 94, 146, 133,
101,131, 116, 111, 84, 137, 115, 122, 106, 144, 109, 123, 116, 111,111, 133, 150]
# 2)创建画布
plt.figure(figsize=(20, 8), dpi=100)
# 3)绘制直方图
# 设置组距
distance = 2
# 计算组数
group_num = int((max(time) - min(time)) / distance)
# 绘制直方图
plt.hist(time, bins=group_num)
# 修改x轴刻度显示
plt.xticks(np.arange(min(time), max(time),2))
# 添加网格显示
plt.grid(linestyle="--", alpha=0.5)
# 添加x, y轴描述信息
plt.xlabel("电影时长大小")
plt.ylabel("电影的数据量")
# 4)显示图像
plt.show()
matplotlib.pyplot.hist(x, bins=None, normed=None, **kwargs)方法说明:
x:数据集
bins:分成了多少个组
**kwargs:其他参数,可以包含绘制时的颜色等
xticks():x轴的刻度和刻度标签
-------------------这里说一下坐标轴刻度和标签的问题-------------------------------
例子1:
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
x = np.arange(30)
y = np.sin(x)
plt.figure(figsize=(12,6))
plt.plot(x, y)
# 设置X轴的刻度间隔
plt.gca().xaxis.set_major_locator(MultipleLocator(3))
# 设置X轴的刻度显示格式
plt.gca().xaxis.set_major_formatter(FormatStrFormatter("%d-K"))
# 自动旋转X轴的刻度,适应坐标轴
plt.gcf().autofmt_xdate()
plt.show()
例子2:
import matplotlib.pyplot as plt
import numpy as np
import datetime
from matplotlib.dates import DayLocator, DateFormatter
x = [datetime.date.today() + datetime.timedelta(i) for i in range(30)]
y = np.sin(np.arange(30))
plt.figure(figsize=(12,6))
plt.plot(x, y)
# 设置X轴的时间间隔,MinuteLocator、HourLocator、DayLocator、WeekdayLocator、MonthLocator、YearLocator
plt.gca().xaxis.set_major_locator(DayLocator(interval=3))
# 设置X轴的时间显示格式
plt.gca().xaxis.set_major_formatter(DateFormatter('%y/%m/%d'))
# 自动旋转X轴的刻度,适应坐标轴
plt.gcf().autofmt_xdate()
plt.show()
例子3:共享坐标轴
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(1)
ax1 =plt.subplot(111)
ax2 = ax1.twinx()
ax1.plot(np.arange(1,5),'g--')
ax1.set_ylabel('ax1',color = 'r')
ax2.plot(np.arange(7,10),'r-')
ax2.set_ylabel('ax2',color = 'g')
plt.show()