Data analysis of the python trio: matplotlib drawing module

matplotlib

A, Matplotlib basics

The basic diagram includes Matplotlib elements

- x轴和y轴  axis   
  水平和垂直的轴线

- x轴和y轴刻度  tick  
  刻度标示坐标轴的分隔,包括最小刻度和最大刻度

- x轴和y轴刻度标签  tick label  
  表示特定坐标轴的值

- 绘图区域(坐标系) axes  
  实际绘图的区域

- 坐标系标题 title  
  实际绘图的区域

- 轴标签 xlabel ylabel  
  实际绘图的区域

Comprising a single curve of FIG.

  • Note: the value of y, x-axis must be a number
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pandas import Series,DataFrame

## 在jupyter 环境使用
%matplotlib inline

x=[1,2,3,4,5]
y=[2,4,6,8,10]

# 绘制直线图 
plt.plot(x,y)

# 绘制抛物线
# linspace再 正π~负π生成10个数
x = np.linspace(-np.pi,np.pi,num=10)
y = x**2

plt.plot(x,y)

# 绘制正弦曲线图
x = x
# 使用sin函数
y = np.sin(x)
plt.plot(x,y)

Comprising a plurality of curves in FIG.

# 连续调用多次plot函数
plt.plot(x,y)
plt.plot(x-1,y+2)

# 也可以在一个plot函数中传入多对X,Y值,在一个图中绘制多个曲线
plt.plot(x,y,x+1,y-1)

Drawing a plurality of curves in a table area: creating an object in the form of table of FIG.

# - a=plt.subplot(row,col,loc) 创建曲线图
# - a.plot(x,y) 绘制曲线图

# subplot(x y z)可以绘制多个子图 : xy表示多大平面图,z表示哪个位置
ax1 = plt.subplot(2,2,1)
ax1.plot(x,y)

ax2 = plt.subplot(222)
ax2.plot(x+1,y-2)

ax3 = plt.subplot(223)
ax3.plot(x+3,y-1)

ax4 = plt.subplot(224)
ax4.plot(x**2,y-2)

Axis limits

#### axis方法:设置x,y轴刻度值的范围
    # plt.axis([xmin,xmax,ymin,ymax])
plt.plot(x,y)
plt.axis([-6,6,-2,2])

# plt.axis('off') 
# 关闭坐标轴 如下图:
plt.plot(x,y)
plt.axis('off')

# 设置画布比例:plt.figure(figsize=(a,b))
        # a:x刻度比例   
        # b:y刻度比例  (2:1)表示x刻度显示为y刻度显示的2倍
plt.figure(figsize=(16,8))
plt.plot(x,y)

Axis label

# - s 标签内容
# - color 标签颜色
# - fontsize 字体大小
# - rotation 旋转角度
# - plt的xlabel方法和ylabel方法  title方法
plt.plot(x,y)
plt.xlabel('haha')
plt.ylabel('hehe')
plt.title('heihei')

legend

#### legend方法
    # 两种传参方法:
        - 分别在plot函数中增加label参数,再调用plt.legend()方法显示
        - 直接在legend方法中传入字符串列表
plt.plot(x,y,label='temp')
plt.plot(x-1,y+3,label='dist')
plt.legend()

legend of parameters

### - loc参数
    # - loc参数用于设置图例标签的位置,一般在legend函数内
    # - matplotlib已经预定义好几种数字表示的位置
plt.plot(x,y,label='temp')
plt.plot(x-1,y+3,label='dist')
plt.legend(loc=3)

String Numerical String Numerical
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 control several columns have the legend, the legend provided in ncol

plt.plot(x,y,label='temp')
plt.plot(x-1,y+3,label='dist')
plt.legend(loc=3,ncol=2)

save Picture

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

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

    figure.savefig的参数选项
        - filename  
          含有文件路径的字符串或Python的文件型对象。图像格式由文件扩展名推断得出,例如,.pdf推断出PDF,.png推断出PNG
          (“png”、“pdf”、“svg”、“ps”、“eps”……)
        - dpi  
          图像分辨率(每英寸点数),默认为100
        - facecolor ,打开保存图片查看 
          图像的背景色,默认为“w”(白色)
fig = plt.figure()

plt.plot(x,y,label='temp')
plt.plot(x-1,y+3,label='dist')
plt.legend(loc=3,ncol=2)

fig.savefig('./123.png',dpi=300)

Set plot style and style

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

plt.plot(x,y,c='red',alpha=0.5,ls='steps',lw=3)

##### 颜色值的方式
    # - 别名
      - color='r'


    # - 合法的HTML颜色名
      - color = 'red'
colour Aliases HTML color names colour Aliases HTML color names
blue b blue green g green
red r red yellow Y yellow
Blue color c cyan black k black
Magenta m magenta white w white
  • HTML hex string

    color = '#eeefff'

  • Normalized to [0, 1] RGB tuple

    color = (0.3, 0.3, 0.4)

transparency

alpha参数

Linear

参数linestyle或ls

Line style description Line style description
'-' solid line ':' dotted line
'--' The dashed line 'steps' Step Line
'-.' Dotted line 'None' / ',' Nothing painting
Linewidth

linewidth或lw参数

Point type
  • shaped marker set point
  • markersize shape size setpoint
mark description mark description
's' square 'p' Pentagon
'h' 1 hexagon 'H' 2 hexagon
'8' Octagon
mark description mark description
'.' point 'x' X
'*' Asterisk '+' plus
',' Pixels
mark description mark description
'The' Circles 'D' diamond
'd' Small diamond '','None',' ',None no
mark description mark description
'1' Corner down tripod '3' Left corner of the tripod
'2' Corner up tripod '4' 一角朝右的三脚架
plt.plot(x,y,marker='2')

# 绘制线      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
data = [1,2,3,3,4,2,5]
plt.hist(data,bins=10)

### 返回值 :

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

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

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

条形图:plt.bar()

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

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

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

# 使用到的函数
bar()、barh()
x = [1,2,3,4,5]
y = [2,4,6,8,10]
# 竖向柱状图
plt.bar(x,y)

# 横向柱状图
plt.barh(x,y)

饼图

【饼图也只有一个参数x】
# pie()  
        饼图适合展示各部分占总体的比例,条形图适合比较各部分的大小

        普通各部分占满饼图
plt.pie([1,3,5])

# 普通未占满饼图:小数/比例
plt.pie([0.2,0.3,0.4])

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

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

    - labeldistance参数设置标签距离圆心的距离(比例值)
    - autopct参数设置比例值小数保留位(%.3f%%);
    - pctdistance参数设置比例值文字距离圆心的距离
    - explode参数设置每一块顶点距圆心的长度(比例值,列表);
    - colors参数设置每一块的颜色(列表);
    - shadow参数为布尔值,设置是否绘制阴影
    - startangle参数设置饼图起始角度
arr=[11,22,31,15]  
plt.pie(arr,labels=['a','b','c','d']) #  labels外层展示参数

#labeldistance参数设置标签距离圆心的距离(比例值)
arr=[11,22,31,15]
plt.pie(arr,labels=['a','b','c','d'],labeldistance=0.3)

#autopct参数设置比例值小数保留位(%.3f%%);
arr=[11,22,31,15]
plt.pie(arr,labels=['a','b','c','d'],labeldistance=0.3,autopct='%.5f%%')

##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])

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

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

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

plt.scatter(x,y)

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

Guess you like

Origin www.cnblogs.com/dengl/p/11803551.html