python数据分析——matplotlib绘图

matplotlib

一、Matplotlib基础知识

Matplotlib中的基本图表包括的元素

  • x轴和y轴 axis
    水平和垂直的轴线
  • x轴和y轴刻度 tick
    刻度标示坐标轴的分隔,包括最小刻度和最大刻度
  • x轴和y轴刻度标签 tick label
    表示特定坐标轴的值
  • 绘图区域(坐标系) axes
    实际绘图的区域
  • 坐标系标题 title
    实际绘图的区域
  • 轴标签 xlabel ylabel
    实际绘图的区域
In [2]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas import Series,DataFrame

包含单条曲线的图

  • 注意:y,x轴的值必须为数字
In [3]:
x=[1,2,3,4,5]
y=[2,4,6,8,10]
plt.plot(x,y)
Out[3]:
[<matplotlib.lines.Line2D at 0x8af9a90>]
  • 绘制抛物线
In [7]:
x = np.linspace(-np.pi,np.pi,num=20)
y = x**2
plt.plot(x,y)
Out[7]:
[<matplotlib.lines.Line2D at 0x62941d0>]
  • 绘制正弦曲线图
In [10]:
x
y = np.sin(x)
plt.plot(x,y)
Out[10]:
[<matplotlib.lines.Line2D at 0x6313940>]

包含多个曲线的图

1、连续调用多次plot函数

In [12]:
plt.plot(x,y)
plt.plot(x+2,y+3)
Out[12]:
[<matplotlib.lines.Line2D at 0x5073668>]

2、也可以在一个plot函数中传入多对X,Y值,在一个图中绘制多个曲线

In [13]:
plt.plot(x,y,x+1,y-2)
Out[13]:
[<matplotlib.lines.Line2D at 0x50fdc88>,
 <matplotlib.lines.Line2D at 0x50fddd8>]

将多个曲线图绘制在一个table区域中:对象形式创建表图

  • a=plt.subplot(row,col,loc) 创建曲线图
  • a.plot(x,y) 绘制曲线图
In [15]:
ax1 = plt.subplot(221)
ax1.plot(x,y)
ax2 = plt.subplot(2,2,2)
ax2.plot(x,y)
ax3 = plt.subplot(2,2,3)
ax3.plot(x,y)
ax4 = plt.subplot(2,2,4)
ax4.plot(x,y)
Out[15]:
[<matplotlib.lines.Line2D at 0x666cd68>]

网格线 plt.gride(XXX)

参数:

- axis
- color:支持十六进制颜色
- linestyle: --  -.  :
- alpha
In [21]:
plt.plot(x,y)
plt.grid(axis='both',c='blue')
  • 绘制一个正弦曲线图,并设置网格
In [16]:
plt.plot(x,y,c='red',alpha=0.7)
Out[16]:
[<matplotlib.lines.Line2D at 0x66ff668>]

坐标轴界限

axis方法:设置x,y轴刻度值的范围

plt.axis([xmin,xmax,ymin,ymax])

In [25]:
plt.plot(x,y)
plt.axis([-6,6,-2,2])
#plt.axis('off')
Out[25]:
[-6, 6, -2, 2]
plt.axis('off')

关闭坐标轴

设置画布比例:plt.figure(figsize=(a,b)) a:x刻度比例 b:y刻度比例 (2:1)表示x刻度显示为y刻度显示的2倍
In [28]:
plt.figure(figsize=(6,6))
plt.plot(x,y)
Out[28]:
[<matplotlib.lines.Line2D at 0x9da7518>]

坐标轴标签

  • s 标签内容
  • color 标签颜色
  • fontsize 字体大小
  • rotation 旋转角度
  • plt的xlabel方法和ylabel方法 title方法
In [33]:
plt.plot(x,y)
plt.xlabel('aaa')
plt.ylabel('bbb')
plt.title('ccc')
Out[33]:
Text(0.5,1,'ccc')

图例

legend方法

两种传参方法:

  • 分别在plot函数中增加label参数,再调用plt.legend()方法显示
  • 直接在legend方法中传入字符串列表
In [44]:
plt.plot(x,y,label='aaa')
plt.plot(x+2,y+3,label='bbb')
plt.legend(loc=0,ncol=2)
Out[44]:
<matplotlib.legend.Legend at 0xb28aa90>

legend的参数

- loc参数
  • loc参数用于设置图例标签的位置,一般在legend函数内
  • matplotlib已经预定义好几种数字表示的位置
字符串数值字符串数值
best 0 center left 6
upper right 1 center right 7
upper left 2 lower center 8
lower left 3 upper center 9
lower right 4 center 10
right 5
 
- ncol参数

ncol控制图例中有几列,在legend中设置ncol

保存图片

使用figure对象的savefig函数来保存图片

fig = plt.figure()---必须放置在绘图操作之前

figure.savefig的参数选项

  • filename
    含有文件路径的字符串或Python的文件型对象。图像格式由文件扩展名推断得出,例如,.pdf推断出PDF,.png推断出PNG (“png”、“pdf”、“svg”、“ps”、“eps”……)
  • dpi
    图像分辨率(每英寸点数),默认为100
  • facecolor ,打开保存图片查看 图像的背景色,默认为“w”(白色)
In [45]:
fig = plt.figure()
plt.plot(x,y,label='aaa')
plt.plot(x+2,y+3,label='bbb')
plt.legend(loc=0,ncol=2)
fig.savefig('./123.png',dpi=500)

设置plot的风格和样式

plot语句中支持除X,Y以外的参数,以字符串形式存在,来控制颜色、线型、点型等要素,语法形式为:
plt.plot(X, Y, 'format', ...)

颜色

参数color或c

颜色值的方式
  • 别名
    • color='r'
  • 合法的HTML颜色名
    • color = 'red'
颜色别名HTML颜色名颜色别名HTML颜色名
蓝色 b blue 绿色 g green
红色 r red 黄色 y yellow
青色 c cyan 黑色 k black
洋红色 m magenta 白色 w white
  • HTML十六进制字符串
    • color = '#eeefff'
  • 归一化到[0, 1]的RGB元组
    • color = (0.3, 0.3, 0.4)
透明度

alpha参数 

线型

参数linestyle或ls

 
线条风格描述线条风格描述
'-' 实线 ':' 虚线
'--' 破折线 'steps' 阶梯线
'-.' 点划线 'None' / ',' 什么都不画
In [52]:
plt.plot(x,y,ls='steps',lw=10)
Out[52]:
[<matplotlib.lines.Line2D at 0xb5d17b8>]
线宽

linewidth或lw参数

点型
  • marker 设置点形
  • markersize 设置点形大小
标记描述标记描述
's' 正方形 'p' 五边形
'h' 六边形1 'H' 六边形2
'8' 八边形
标记描述标记描述
'.' 'x' X
'*' 星号 '+' 加号
',' 像素
标记描述标记描述
'o' 圆圈 'D' 菱形
'd' 小菱形 '','None',' ',None
标记描述标记描述
'1' 一角朝下的三脚架 '3' 一角朝左的三脚架
'2' 一角朝上的三脚架 '4' 一角朝右的三脚架
In [51]:
plt.plot(x,y,marker='d',markersize=10)
Out[51]:
[<matplotlib.lines.Line2D at 0xb56f320>]
In [85]:
# 绘制线      plt.plot(x1,y1,x2,y2)
# 网格线      plt.grid(True)  axes.grid(color,ls,lw,alpha)
# 获取坐标系  plt.subplot(n1,n2,n3)
# 坐标轴标签  plt.xlabel() plt.ylabel()
# 坐标系标题  plt.title()
# 图例        plt.legend([names],ncol=2,loc=1)  plt.plot(label='name')
# 线风格      --  -. : None  step
# 图片保存    figure.savefig()
# 点的设置    marker markersize markerfacecolor markeredgecolor\width
# 坐标轴刻度  plt.xticks(刻度列表,刻度标签列表) plt.yticks()
#             axes.set_xticks(刻度列表) axes.set_xticklabels(刻度标签列表)

三、2D图形

直方图

  • 是一个特殊的柱状图,又叫做密度图。

【直方图的参数只有一个x!!!不像条形图需要传入x,y】

plt.hist()的参数

  • bins
    直方图的柱数,可选项,默认为10
  • color
    指定直方图的颜色。可以是单一颜色值或颜色的序列。如果指定了多个数据集合,例如DataFrame对象,颜色序列将会设置为相同的顺序。如果未指定,将会使用一个默认的线条颜色
  • orientation
    通过设置orientation为horizontal创建水平直方图。默认值为vertical
In [55]:
data = [1,2,3,3,4,2,5]
plt.hist(data,bins=10)
Out[55]:
(array([1., 0., 2., 0., 0., 2., 0., 1., 0., 1.]),
 array([1. , 1.4, 1.8, 2.2, 2.6, 3. , 3.4, 3.8, 4.2, 4.6, 5. ]),
 <a list of 10 Patch objects>)

返回值 :

1: 直方图向量,是否归一化由参数normed设定

2: 返回各个bin的区间范围

3: 返回每个bin里面包含的数据,是一个list

条形图:plt.bar()

  • 参数:第一个参数是索引。第二个参数是数据值。第三个参数是条形的宽度

-【条形图有两个参数x,y】

  • width 纵向设置条形宽度
  • height 横向设置条形高度

bar()、barh()

In [57]:
num = [1,2,3,4,5]
count = [2,4,6,8,10]
plt.barh(num,count)
Out[57]:
<BarContainer object of 5 artists>

水平条形图

barh()

饼图

【饼图也只有一个参数x】

pie()
饼图适合展示各部分占总体的比例,条形图适合比较各部分的大小

普通各部分占满饼图

普通未占满饼图:小数/比例

饼图阴影、分裂等属性设置

labels参数设置每一块的标签;

labeldistance参数设置标签距离圆心的距离(比例值)

autopct参数设置比例值小数保留位(%.3f%%);

pctdistance参数设置比例值文字距离圆心的距离

explode参数设置每一块顶点距圆心的长度(比例值,列表);

colors参数设置每一块的颜色(列表);

shadow参数为布尔值,设置是否绘制阴影

startangle参数设置饼图起始角度

In [59]:
plt.pie([0.2,0.5])
Out[59]:
([<matplotlib.patches.Wedge at 0xb890b00>,
  <matplotlib.patches.Wedge at 0xb890f98>],
 [Text(0.889919,0.646564,''), Text(-1.04616,0.339919,'')])
In [58]:
arr=[11,22,31,15]
plt.pie(arr,labels=['a','b','c','d'])
Out[58]:
([<matplotlib.patches.Wedge at 0xb8536a0>,
  <matplotlib.patches.Wedge at 0xb853b70>,
  <matplotlib.patches.Wedge at 0xb85e0f0>,
  <matplotlib.patches.Wedge at 0xb85e630>],
 [Text(0.996424,0.465981,'a'),
  Text(-0.195798,1.08243,'b'),
  Text(-0.830021,-0.721848,'c'),
  Text(0.910034,-0.61793,'d')])
In [60]:
#labeldistance参数设置标签距离圆心的距离(比例值)
arr=[11,22,31,15]
plt.pie(arr,labels=['a','b','c','d'],labeldistance=0.3)
Out[60]:
([<matplotlib.patches.Wedge at 0xb8ce9b0>,
  <matplotlib.patches.Wedge at 0xb8ceeb8>,
  <matplotlib.patches.Wedge at 0xb8d7438>,
  <matplotlib.patches.Wedge at 0xb8d7978>],
 [Text(0.271752,0.127086,'a'),
  Text(-0.0533994,0.295209,'b'),
  Text(-0.226369,-0.196868,'c'),
  Text(0.248191,-0.168526,'d')])
In [61]:
#autopct参数设置比例值小数保留位(%.3f%%);
arr=[11,22,31,15]
plt.pie(arr,labels=['a','b','c','d'],labeldistance=0.3,autopct='%.6f%%')
Out[61]:
([<matplotlib.patches.Wedge at 0xb914208>,
  <matplotlib.patches.Wedge at 0xb914940>,
  <matplotlib.patches.Wedge at 0xb91f0f0>,
  <matplotlib.patches.Wedge at 0xb91f860>],
 [Text(0.271752,0.127086,'a'),
  Text(-0.0533994,0.295209,'b'),
  Text(-0.226369,-0.196868,'c'),
  Text(0.248191,-0.168526,'d')],
 [Text(0.543504,0.254171,'13.924050%'),
  Text(-0.106799,0.590419,'27.848101%'),
  Text(-0.452739,-0.393735,'39.240506%'),
  Text(0.496382,-0.337053,'18.987341%')])
In [62]:
##explode参数设置每一块顶点距圆心的长度(比例值,列表);
arr=[11,22,31,15]
plt.pie(arr,labels=['a','b','c','d'],labeldistance=0.3,shadow=True,explode=[0.2,0.3,0.2,0.4])
Out[62]:
([<matplotlib.patches.Wedge at 0xb958390>,
  <matplotlib.patches.Wedge at 0xb958b38>,
  <matplotlib.patches.Wedge at 0xb960390>,
  <matplotlib.patches.Wedge at 0xb960b38>],
 [Text(0.45292,0.21181,'a'),
  Text(-0.106799,0.590419,'b'),
  Text(-0.377282,-0.328113,'c'),
  Text(0.579113,-0.393228,'d')])
In [63]:
#startangle参数设置饼图起始角度
arr=[11,22,31,15]
plt.pie(arr,labels=['a','b','c','d'],startangle=50)
Out[63]:
([<matplotlib.patches.Wedge at 0xb99e438>,
  <matplotlib.patches.Wedge at 0xb99e908>,
  <matplotlib.patches.Wedge at 0xb99ee48>,
  <matplotlib.patches.Wedge at 0xb9a93c8>],
 [Text(0.283527,1.06283,'a'),
  Text(-0.955049,0.545785,'b'),
  Text(0.0194406,-1.09983,'c'),
  Text(1.05832,0.299929,'d')])
 

%m.nf m 占位 n 小数点后保留几位 f 是以float格式输出

散点图:因变量随自变量而变化的大致趋势

【散点图需要两个参数x,y,但此时x不是表示x轴的刻度,而是每个点的横坐标!】

scatter()

In [64]:
x = np.random.randint(0,10,size=(20,))
y = np.random.randint(0,10,size=(20,))

plt.scatter(x,y,marker='d',c="rbgy") 设置不同的散点颜色

In [67]:
plt.scatter(x,y,c='rgyb')
Out[67]:
<matplotlib.collections.PathCollection at 0xca6bba8>
In [68]:
x = [1,2,3,4,5]
y = [2,4,6,8,10]
plt.scatter(x,y)
Out[68]:
<matplotlib.collections.PathCollection at 0xcacf630>
posted @ 2019-10-08 16:05  陪伴is最长情的告白  阅读(790)  评论(0编辑  收藏  举报