matplotlib.pyplot学习

Python数据可视化

matplotlib.pyplot官网:https://matplotlib.org/api/pyplot_api.html
import matplotlib.pyplot as plt

plt.plot()

plot()这个函数是画线图用的,比如直线y=x,抛物线y=x**2,或者一个圆

PropertyDescription
agg_filtera filter function, which takes a (m, n, 3) float array and a dpi value, and returns a
alphafloat (0.0 transparent through 1.0 opaque)
animatedbool
antialiased or aa[True False]
clip_boxa Bbox instance
clip_onbool
clip_path[(Path, Transform) Patch None]
color or cany matplotlib color
containsa callable function
dash_capstyle[‘butt’ ‘round’ ‘projecting’]
dash_joinstyle[‘miter’ ‘round’ ‘bevel’]
dashessequence of on/off ink in points
drawstyle[‘default’ ‘steps’ ‘steps-pre’ ‘steps-mid’ ‘steps-post’]
figurea Figure instance
fillstyle[‘full’
gidan id string
labelobject
linestyle or ls[‘solid’ ‘dashed’, ‘dashdot’, ‘dotted’ (offset, on-off-dash-seq) ‘-’ ‘–’ ‘-.’ ‘:’ ‘None’ ’ ’ ‘’]
linewidth or lwfloat value in points
markerA valid marker style
markeredgecolor or mecany matplotlib color
markeredgewidth or mewfloat value in points
markerfacecolor or mfcany matplotlib color
markerfacecoloralt or mfcaltany matplotlib color
markersize or msfloat
markevery[None int length-2 tuple of int slice list/array of int float length-2 tuple of float]
path_effectsAbstractPathEffect
pickerfloat distance in points or callable pick function fn(artist, event)
pickradiusfloat distance in points
rasterizedbool or None
sketch_params(scale: float, length: float, randomness: float)
snapbool or None
solid_capstyle[‘butt’ ‘round’ ‘projecting’]
solid_joinstyle[‘miter’ ‘round’ ‘bevel’]
transforma matplotlib.transforms.Transform instance
urla url string
visiblebool
xdata1D array
ydata1D array
zorderfloat

例如: plot(x, y, color=‘r’, linestyle=‘dashed’, marker=‘o’,
markerfacecolor=‘blue’, markersize=12)
其中x是自变量,y是x根据某种关系得到的值,c或者color是线的颜色 ,其实都是字面意思,像marker就是标记(x,y)的标记

#!/usr/bin/python
# -*- coding:utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt


x = np.arange(0,10,1)  #取(0,10)的点
y = x				   #函数

plt.plot(x, y, color='r', linestyle='dashed', marker='o',
     markerfacecolor='blue', markersize=12)      #画图   红线、虚线、圆点、蓝点、大小是12

plt.grid() #网格线显示
plt.show() #图像显示

在这里插入图片描述
注:颜色和线条:

       b    blue   蓝      .     point              -     solid
       g    green  绿      o     circle             :     dotted
       r    red    红      x     x-mark             -.    dashdot 
       c    cyan   青      +     plus               --    dashed   
       m    magenta 品红   *     star             (none)  no line
       y    yellow 黄      s     square
       k    black  黑      d     diamond
       w    white  白      v     triangle (down)
                           ^     triangle (up)
                           <     triangle (left)
                           >     triangle (right)
                           p     pentagram 五角星
                           h     hexagram  六角星

注里面的类容来自------>原文:https://blog.csdn.net/xiaotao_1/article/details/79100163

plt.axvline() axhline()

与其对应的有一个是ayvline()
例如:axvline(8) # x=8参考线
在这里插入图片描述
过y轴的参考线同理

plt.title()

表格标题

plt.xticks()

与其对应的是yticks(),其特点是我设置什么值,它数轴就只出现什么值
例如:plt.xticks([1,2,3,4])会使x轴标度变为
12

plt.tick_params()

设置坐标轴的刻度参数,这参数包括位置、颜色、大小、等等

plt.lengend()

设置图例legend, 可以直接设置在plt.plot的label属性中,然后plt.lengend()显示
loc顺序: “先上中下,再左中右” 默认上左, shadow default: False

例如:plt.legend(loc=‘upper left’,shadow=False, fontsize=12)

#!/usr/bin/python
# -*- coding:utf-8 -*-

import numpy as np
import matplotlib.pyplot as plt


x = np.arange(0,10,1)  #取(0,10)的点
y = x				   #函数

plt.title('hahaha')
plt.plot(x, y, color='r', linestyle='dashed', marker='o',
     markerfacecolor='blue', markersize=12 , label='y=x')      #画图
#plt.xticks([1,2,3,4])
plt.legend(loc='upper left',shadow=False, fontsize=12)
plt.grid() #网格线显示
plt.show() #图像显示

在这里插入图片描述

plt.grid()

显示网格
函数:def grid(b=None, which=‘major’, axis=‘both’, **kwargs)

plt.scatter()

散点图
plt.scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, *, data=None, **kwargs)
x,y:表示的是大小为(n,)的数组,也就是我们即将绘制散点图的数据点
s:是一个实数或者是一个数组大小为(n,),这个是一个可选的参数。
c:表示的是颜色,也是一个可选项。默认是蓝色’b’,表示的是标记的颜色,或者可以是一个表示颜色的字符,或者是一个长度为n的表示颜色的序列等等,感觉还没用到过现在不解释了。但是c不可以是一个单独的RGB数字,也不可以是一个RGBA的序列。可以是他们的2维数组(只有一行)。
marker:表示的是标记的样式,默认的是’o’。
cmap:Colormap实体或者是一个colormap的名字,cmap仅仅当c是一个浮点数数组的时候才使用。如果没有申明就是image.cmap
norm:Normalize实体来将数据亮度转化到0-1之间,也是只有c是一个浮点数的数组的时候才使用。如果没有申明,就是默认为colors.Normalize。
vmin,vmax:实数,当norm存在的时候忽略。用来进行亮度数据的归一化。
alpha:实数,0-1之间。
linewidths:也就是标记点的长度。

plt.bar()

柱状图参数:
(1) X
(2) Y
(3) Color
(4) Alpha透明度
(5) Align粗细
(6) plt.text(x,y,%x %y ,ha=‘center’) 这句话可以把柱状图标上数字,ha也就是标注的位置

plt.hist()

直方图
属性:bins粗度
def hist(x, bins=None, range=None, density=None, weights=None, cumulative=False,
bottom=None, histtype=‘bar’, align=‘mid’, orientation=‘vertical’,
rwidth=None, log=False, color=None, label=None, stacked=False,
normed=None, hold=None, data=None, **kwargs)

plt.pie()

饼图
def pie(x, explode=None, labels=None, colors=None, autopct=None,
pctdistance=0.6, shadow=False, labeldistance=1.1, startangle=None,
radius=None, counterclock=True, wedgeprops=None, textprops=None,
center=(0, 0), frame=False, rotatelabels=False, hold=None, data=None)

plt.fill_between()

修饰图
def fill_between(x, y1, y2=0, where=None, interpolate=False, step=None,
hold=None, data=None, **kwargs)

plt.imshow()

热图
def imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None,
vmin=None, vmax=None, origin=None, extent=None, shape=None,
filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None,
hold=None, data=None, **kwargs)

plt.colorbar()

颜色条
def colorbar(mappable=None, cax=None, ax=None, **kw)

plt.pcolormesh()

cmap:
cm_light = mpl.colors.ListedColormap([’#A0FFA0’, ‘#FFA0A0’, ‘#A0A0FF’])
cm_dark = mpl.colors.ListedColormap([‘g’, ‘r’, ‘b’])

plt.pcolormesh()会根据y_predict的结果自动在cmap里选择颜色

plt.annotate()

函数解析:函数用于标注文字

我是管小亮:)博主讲的不错,链接:https://blog.csdn.net/TeFuirnever/article/details/88946088

plt.ylim() 、 plt.xlim()

坐标轴取值

plt.ylabel() 、 plt.xlabel()

坐标轴换名

ax = plt.gca()

ax = plt.gca()获取当前坐标轴

用ax代表坐标轴操作

#移动坐标轴:设置零点在坐标轴的位置 ,set_position(tuple) 元素为tuple

ax.spines[‘left’].set_position((‘data’,0)) # data 表示position是相 对于数据坐标系

ax.yaxis.set_ticks_position(‘left’) # y轴’right’: 刻度值显示在 right坐标轴上

ax.spines[‘bottom’].set_position((‘data’,0))

ax.xaxis.set_ticks_position(‘bottom’) # x轴top:ticks值显示在top坐 标轴上

ax.spines[‘right’].set_color(‘none’) # 隐藏top和right边框
ax.spines[‘top’].set_color(‘none’)

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值