Python数据分析——Matplotlib

基础语法

plt.plot(x,y,format_string,**kwargs)

说明:
----x:x轴数据,列表或数组,可选
----y:y轴数据,列表或数组,可选
----format_string:控制曲线的格式字符串,可选
----**kwargs:第二组或更多,(x,y,format_string)

plot函数的一般的调用形式

单条线:

plot([x], y, [fmt], data=None, **kwargs)

多条线一起画

plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs)

  可选参数[fmt] 是一个字符串来定义图的基本属性如:颜色(color),点型(marker),线型(linestyle),

  具体形式 fmt = ‘[color][marker][line]’

  fmt接收的是每个属性的单个字母缩写,例如:

plot(x, y, 'bo-')  # 蓝色圆点实线

  若属性用的是全名则不能用fmt参数来组合赋值,应该用关键字参数对单个属性赋值如:

plot(x,y2,color='green', marker='o', linestyle='dashed', linewidth=1, markersize=6)
plot(x,y3,color='#900302',marker='+',linestyle='-')

常见的颜色参数:Colors
也可以对关键字参数color赋十六进制的RGB字符串如 color=’#900302’
============= ===============================
character color
============= ===============================
'b' blue 蓝
'g' green 绿
'r' red 红
'c' cyan 蓝绿
'm' magenta 洋红
'y' yellow 黄
'k' black 黑
'w' white 白
============= ===============================
点型参数Markers,如:marker=’+’ 这个只有简写,英文描述不被识别
============= ===============================
character description
============= ===============================
'.' point marker
',' pixel marker
'o' circle marker
'v' triangle_down marker
'^' triangle_up marker
'<' triangle_left marker
'>' triangle_right marker
'1' tri_down marker
'2' tri_up marker
'3' tri_left marker
'4' tri_right marker
's' square marker
'p' pentagon marker
'*' star marker
'h' hexagon1 marker
'H' hexagon2 marker
'+' plus marker
'x' x marker
'D' diamond marker
'd' thin_diamond marker
'|' vline marker
'_' hline marker
============= ===============================
线型参数Line Styles,linestyle=’-’

=============    ===============================
character     		   description
=============    ===============================
``'-'``        		  solid line style 实线
``'--'``       			  dashed line style 虚线
``'-.'``       			  dash-dot line style 点画线
``':'``        			  dotted line style 点线
=============    ===============================

实例

import numpy as np
import pandas as pd
from pandas import Series,DataFrame
import matplotlib.pyplot as plt


def   fun1():
    x = np.arange(10)
    y = x + 1
    # 获取画板
    plt.figure()
    # x表示x轴所有的点
# y表示y轴所有的点
# 显示设置
# File | Settings | Tools | Python Scientific | Show plots in toolwindow
plt.plot(x, y, ':',color = 'r')
plt.show()
fun1()


def fun2():
    x = np.arange(10)
    y = x ** 2
    plt.figure()
plt.plot(x, y, '--', color = 'b')
plt.show()
fun2()


def fun3():
    x = np.linspace(1, 10, 100)
    y = np.cos(x)
    z = np.sin(x)
    plt.figure()
    plt.plot(x, y, '-1')
plt.plot(x, z, '-2')
plt.show()
fun3()


def fun4():
    x = np.arange(10)
    y = x ** 2
    # figszie属性可以用来设置画布大小,单位英寸
    plt.figure(figsize = (8, 4))
    plt.plot(x, y, '-x', color = 'r')
    
    #设置x,y轴的标注
    plt.xlabel('time')
    plt.ylabel('speed')
    
    #修改刻度,轴上显示的值
    plt.xticks(np.arange(10))
    #plt.xticks(np.arange(10), ["a","b","c","d","e","f","g","h","i","j"])
    
    #获取ax,然后在上面写字
    ax = plt.gca() #gca=>get current axis
    # list基本操作zip()函数
    for i,j in zip(x, y): #[1,2,3,4] [1,4,9,16] => [(1,1),(2,4),(3,9),(4,16)]
        #ax.text(x点,y点,文字内容)
        #bbox给文字加一个框,facecolor框的背景色,alpha透明度
        ax.text(i + 0.2, j, j, bbox=dict(facecolor='red', alpha=0.8))
    #给当前画布加格
plt.grid(True)
plt.show()
fun4()


aList = [3, 5, 7, 9, 11]
bList = ['a', 'b', 'c', 'd']
(3, 'a') in zip(aList, bList)

aList = [3, 5, 7, 9, 11]
bList = ['a', 'b', 'c', 'd']
for a, b in zip(aList, bList):
    print(a, b)

a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
l = zip(a,b)
k = zip(a,c)
print(list(l))
print(list(k))


kind = {
    
    "circle":"o","star":"*","traggle_down":"v","dash_dot":"-","dash_line":"--","x-mark":"x"}
kind.keys()

kind = {
    
    "circle":"o","star":"*","traggle_down":"v","dash_dot":"-","dash_line":"--","x-mark":"x"}
for index, key in zip(np.arange(6), kind.keys()):
    print(index, key)



def fun5():
    x = np.arange(50)
    #六条线,六个颜色
    colors = ['r','y','g','b','c','m']
    #字典中表示六条线的不同样式
    kind = {
    
    "circle":"o","star":"*","traggle_down":"v","dash_dot":"-","dash_line":"--","x-mark":"x"}
    
    plt.figure(figsize = (12,8))
    for index, key in zip(np.arange(6), kind.keys()):
        y = np.random.randn(50)
        plt.plot(x, y, kind[key],color = colors[index], label = key)#label图例的内容
        plt.legend()
    plt.show()
fun5()

#plt.rcParams['font.sans-serif'] = ['SimHei']
#plt.rcParams['axes.unicode_minus'] = False

#n = np.linspace(-5, 4, 30)
#m1 = 3 * n + 2
#m2 = n ** 2

#plt.xlabel('时间')
#plt.ylabel('心情')

#plt.plot(n, m1, color='r', linewidth=1.5, linestyle='-', label='女生购物欲望')
#plt.plot(n, m2, 'b', label='男生购物欲望')
#plt.legend()

#plt.show()






# plt.annotate(str, xy=data_point_position, xytext=annotate_position, va="center",  ha="center", xycoords="axes fraction", textcoords="axes fraction", bbox=annotate_box_type, arrowprops=arrow_style)
    # str是给数据点添加注释的内容,支持输入一个字符串
    # xy=是要添加注释的数据点的位置
    # xytext=是注释内容的位置
    # bbox=是注释框的风格和颜色深度,fc越小,注释框的颜色越深,支持输入一个字典
    # va="center",  ha="center"表示注释的坐标以注释框的正中心为准,而不是注释框的左下角(v代表垂直方向,h代表水平方向)
    # xycoords和textcoords可以指定数据点的坐标系和注释内容的坐标系,通常只需指定xycoords即可,textcoords默认和xycoords相同
    # arrowprops可以指定箭头的风格支持,输入一个字典
plt.annotate()的详细参数可用__doc__查看,如:print(plt.annotate.__doc__)

def fun6():
    plt.figure(figsize=(8,6))
    x = np.linspace(-np.pi, np.pi, 256)
    c = np.cos(x)
    s = np.sin(x)
    plt.plot(x, c, '-')
    plt.plot(x, s, '--')
    
    #限制x轴和y轴的刻度范围
    plt.xlim([-4, 4])
    plt.ylim([-1, 1])
    
    #修改x轴和y轴上显示的刻度
    #转义字符“$\$”
    plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],["$-\pi$","$-\pi/2$",0,"$\pi/2$","$\pi$"])
    plt.yticks([-1, 0, 1])
    
    #去除上边框和右边框
    ax = plt.gca()
    ax.spines['right'].set_color('none')
    ax.spines['top'].set_color('none')
    
    #将底边框上移,将左边框右移
    ax.spines['bottom'].set_position(('data',0))
    ax.spines['left'].set_position(('data',0))
    
    t = 2 * np.pi / 3
    y = np.sin(t)
    
    #画点使用scatter   50表示半径
    plt.scatter(t, y, 50, color = 'r')
    plt.annotate("y=sin(x)", xy=(t,y), textcoords="offset points", xytext=(30,30), arrowprops=dict(arrowstyle="->",connectionstyle="arc3,rad=.5"))
    plt.show()

柱状图

bar()的构造函数(产生一个柱状图)
bar(x,height, width,*,align=‘center’,**kwargs)
–x:包含所有柱子的下标的列表

–height:包含所有柱子的高度值的列表

–width:每个柱子的宽度。可以指定一个固定值,那么所有的柱子都是一样的宽。或者设置一个列表,这样可以分别对每个柱子设定不同的宽度。

–align:柱子对齐方式,有两个可选值:center和edge。center表示每根柱子是根据下标来对齐, edge则表示每根柱子全部以下标为起点,然后显示到下标的右边。如果不指定该参数,默认值是center。

其他可选参数有:

–color:每根柱子呈现的颜色。同样可指定一个颜色值,让所有柱子呈现同样颜色;或者指定带有不同颜色的列表,让不同柱子显示不同颜色。

–edgecolor:每根柱子边框的颜色。同样可指定一个颜色值,让所有柱子边框呈现同样颜色;或者指定带有不同颜色的列表,让不同柱子的边框显示不同颜色。

–linewidth:每根柱子的边框宽度。如果没有设置该参数,将使用默认宽度,默认是没有边框。

–tick_label:每根柱子上显示的标签,默认是没有内容。

–xerr:每根柱子顶部在横轴方向的线段。如果指定一个固定值,所有柱子的线段将一直长;如果指定一个带有不同长度值的列表,那么柱子顶部的线段将呈现不同长度。

–yerr:每根柱子顶端在纵轴方向的线段。如果指定一个固定值,所有柱子的线段将一直长;如果指定一个带有不同长度值的列表,那么柱子顶部的线段将呈现不同长度。

–ecolor:设置 xerr 和 yerr 的线段的颜色。同样可以指定一个固定值或者一个列表。

–capsize:这个参数很有趣, 对xerr或者yerr的补充说明。一般为其设置一个整数,例如 10。如果你已经设置了yerr 参数,那么设置 capsize 参数,会在每跟柱子顶部线段上面的首尾部分增加两条垂直原来线段的线段。对 xerr 参数也是同样道理。可能看说明会觉得绕,如果你看下图就一目了然了。

–error_kw:设置 xerr 和 yerr 参数显示线段的参数,它是个字典类型。如果你在该参数中又重新定义了 ecolor 和 capsize,那么显示效果以这个为准。

–orientation:设置柱子是显示方式。设置值为 vertical ,那么显示为柱形图。如果设置为 horizontal 条形图。不过 matplotlib 官网不建议直接使用这个来绘制条形图,使用barh来绘制条形图。

Guess you like

Origin blog.csdn.net/m0_52000372/article/details/117387614