Matplotlib数据可视化

'''
    Matplotlib作为数据科学的的必备库,算得上是python可视化领域的元老,更是很多高级可视化库的底层
    基础,其重要性不言而喻。

    Matplotlib 是 Python 的绘图库。 它可与 NumPy 一起使用,提供了一种有效的 MatLab 开源替代方案。

    matplotlib.pyplot是一个命令风格函数的集合,使matplotlib的机制更像 MATLAB。
    每个绘图函数对图形进行一些更改:例如,创建图形,在图形中创建绘图区域,在绘图区域绘制一些线条
    ,使用标签装饰绘图等。
    在matplotlib.pyplot中,各种状态跨函数调用保存,以便跟踪诸如当前图形和绘图区域之类的东西,
    并且绘图函数始终指向当前轴域(请注意,这里和文档中的大多数位置中的『轴域』(axes)是指图形的
    一部分(两条坐标轴围成的区域),而不是指代多于一个轴的严格数学术语)。
        将 pyplot 导入为 plt ,这是使用 pylot 的 python 程序的传统惯例
    调用 plot 的 .plot 方法绘制一些坐标。plt.plot 在后台『绘制』这个绘图,但绘制了想要的一切之后,
    需要把它带到屏幕上。
    这个窗口是一个 matplotlib 窗口,它允许我们查看图形,以及与它进行交互和访问。
    可以将鼠标悬停在图表上,并查看通常在右下角的坐标。 也可以使用按钮。
    ★用matplotlib画二维图像时,默认情况下的横坐标和纵坐标显示的值有时达不到自己的需求,需要借
    助xticks()和yticks()分别对横坐标x-axis和纵坐标y-axis进行设置。

    ★xticks()中有3个参数:xticks(locs, [labels], **kwargs)  # Set locations and labels
    locs参数为数组参数(array_like, optional),表示x-axis的刻度线显示标注的地方,即ticks放置的地
    方,第二个参数也为数组参数(array_like, optional),可以不添加该参数,表示在locs数组表示的位
    置添加的标签,labels不赋值,在这些位置添加的数值即为locs数组中的数。
    ★Figure对象可以拥有自己的文字、线条以及图像等简单类型的Artist。
    缺省的坐标系统为像素点,但是可以通过设置Artist对象的transform属性修改坐标系的转换方式。
    最常用的Figure对象的坐标系是以左下角为坐标原点(0,0),右上角为坐标(1,1)。

    ★Figure语法
    ★fig = figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)
    ★num:图像编号或名称,数字为编号 ,字符串为名称
    ★figsize:指定figure的宽和高,单位为英寸;
    ★dpi参数指定绘图对象的分辨率,即每英寸多少个像素,缺省值为80   1英寸等于2.5cm,A4纸是 21*30cm的纸张
    ★facecolor:背景颜色
    ★edgecolor:边框颜色
    ★frameon:是否显示边框
    *******************plt.plot***********************
    ★plt.plot(x, y, format_string, **kwargs)
    函数的本质就是根据点连接线。plot()是一个通用命令,并且可接受任意数量的参数。

    ★参数             说明
    ★x                X轴数据,列表[列表],元组(元组)或数组np.array,pd.Series,可传入多组x, y
    ★y                Y轴数据,列表或数组
                       x,y可以不等长
    ★format_string    控制曲线的格式字符串,可选,format_string 由颜色、风格、标记等字符组成
                       "格式控制字符串"最多可以包括三部分, "颜色", "点型", "线型"
    ★**kwargs         第二组或更多(x,y,format_string),可画多条曲线
	*******************plt.plot***********************
    ★plt.plot(x, y, format_string, **kwargs)
    函数的本质就是根据点连接线。plot()是一个通用命令,并且可接受任意数量的参数。

    ★参数             说明
    ★x                X轴数据,列表[列表],元组(元组)或数组np.array,pd.Series,可传入多组x, y
    ★y                Y轴数据,列表或数组
                       x,y可以不等长
    ★format_string    控制曲线的格式字符串,可选,format_string 由颜色、风格、标记等字符组成
                       "格式控制字符串"最多可以包括三部分, "颜色", "点型", "线型"
    ★**kwargs         第二组或更多(x,y,format_string),可画多条曲线
'''

线条

'''
*****************  Controlling line properties  *****************

    ★plot 函数在官方文档的语法中只要求填入不定长参数,实际可以填入的主要参数如下:

    ★参数名称 说明
    ★color 接收特定 string,指定线条的颜色。默认为 None。
                "颜色"格式控制字符串可以输入英文全称, 如"red",
                也可十六进制RGB字符串'#1f77b4', '#ff7f0e'
    ★linestyle 接收特定 string。指定线条类型,默认为“-“
    ★marker 接收特定 string。表示绘制的点的类型。默认为 None
    ★alpha 接收 0-1 的小数。表示点的透明度。默认为 None
    ★在 pyplot 中几乎所有的默认属性都是可以控制的,例如视图窗口大小以及每英寸点数、 线条宽度、
    颜色和样式、坐标轴、坐标和网格属性、文本、字体等
'''

颜色控制符

'''
*****************  颜色控制符  *****************

    ★要想使用丰富,炫酷的图标,可以使用更复杂的格式设置,主要颜色,线的样式,点的样式。
    ★默认的情况下,只有一条线,是蓝色实线。多条线的情况下,生成不同颜色的实线。

    ★color 接收特定 string,指定线条的颜色。默认为 None。
                "颜色"格式控制字符串可以输入英文全称, 如"red",
                也可十六进制RGB字符串'#1f77b4', '#ff7f0e'                

    ★字符           颜色
    ★'b'            蓝色
    ★'g'            绿色
    ★'r'            红色
    ★'c'            青色
    ★'m'            品红色
    ★'y'            黄色
    ★'k'            黑色
    ★'w'            白色
'''

https://finthon.com/matplotlib-color-list/

线条控制符

'''
*****************  线形控制符  *****************

    ★字符 类型
    ★'-' 实线
    ★'--' 虚线
    ★'-.' 虚点线
    ★':' 点线
    ★' ' 空类型,不显示线
'''
'''
*****************  点(标记)的类型控制符  *****************

    ★'.' 点
    ★',' 像素点
    ★'o' 圆点

    ★'^' 上三角点
    ★'v' 下三角点
    ★'<' 左三角点
    ★'>' 右三角点

    ★'1' 下三叉点
    ★'2' 上三叉点
    ★'3' 左三叉点
    ★'4' 右三叉点

    ★'s' 正方点
    ★'p' 五角点
    ★'*' 星形点
    ★'h' 六边形1
    ★'H' 六边形2

    ★'+' 加号点
    ★'x' 乘号点
    ★'D' 实心菱形点
    ★'d' 细菱形点
    ★'_' 横线点
    ★'|' 竖线点
'''
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-np.pi,np.pi,256,endpoint=True)
y_sin = np.sin(x)
y_cos = np.cos(x)
sin_fig = plt.figure('x--sinx',figsize=(4,2),facecolor='blue')
cos_fig = plt.figure('x--cos',figsize=(4,2),facecolor='wheat')
ax_sin = sin_fig.gca()
ax_cos = cos_fig.gca()
ax_sin.plot(x,y_sin)
ax_cos.plot(x,y_cos)
ax_cos = cos_fig.add_axes([0.15,0.2,0.3,0.1])
plt.show()

在这里插入图片描述

set_titcks

'''
*****************  Setting ticks  *****************

    ★用matplotlib画二维图像时,默认情况下的横坐标和纵坐标显示的值有时达不到自己的需求,需要借
    助xticks()和yticks()分别对横坐标x-axis和纵坐标y-axis进行设置。

    ★xticks()中有3个参数:xticks(locs, [labels], **kwargs)  # Set locations and labels
    locs参数为数组参数(array_like, optional),表示x-axis的刻度线显示标注的地方,即ticks放置的地
    方,第二个参数也为数组参数(array_like, optional),可以不添加该参数,表示在locs数组表示的位
    置添加的标签,labels不赋值,在这些位置添加的数值即为locs数组中的数。
    #xticks()函数中,locs参数为数组x,即1到12所有的整数,
    #即画出的图像会在这12个位置画出ticks,即上图中的刻度线。
    #当赋予labels的值为空时,则在locs决定的位置上虽然会画出ticks,但不会显示任何值。
'''
import numpy as np
import matplotlib.pyplot as plt
import calendar
x = range(1,13,1)
y = range(1,13,1)
plt.xticks(x, calendar.month_name[1:13],color='#ff00ff',rotation=60)
plt.yticks([1,5,10], calendar.month_name[1:4], color='#00ff00',rotation=30)
plt.xlabel('x')
plt.ylabel('y')
plt.title('x-y')
plt.plot(x,y)
plt.show()
'''
*****************  Setting ticks  *****************

    ★用matplotlib画二维图像时,默认情况下的横坐标和纵坐标显示的值有时达不到自己的需求,需要借
    助xticks()和yticks()分别对横坐标x-axis和纵坐标y-axis进行设置。

    ★xticks()中有3个参数:xticks(locs, [labels], **kwargs)  # Set locations and labels
    locs参数为数组参数(array_like, optional),表示x-axis的刻度线显示标注的地方,即ticks放置的地
    方,第二个参数也为数组参数(array_like, optional),可以不添加该参数,表示在locs数组表示的位
    置添加的标签,labels不赋值,在这些位置添加的数值即为locs数组中的数。
    #xticks()函数中,locs参数为数组x,即1到12所有的整数,
    #即画出的图像会在这12个位置画出ticks,即上图中的刻度线。
    #当赋予labels的值为空时,则在locs决定的位置上虽然会画出ticks,但不会显示任何值。
'''
import numpy as np
import matplotlib.pyplot as plt
import calendar
x = range(1,13,1)
y = range(1,13,1)
plt.xticks(x, calendar.month_name[1:13],color='#ff00ff',rotation=60)
plt.yticks([1,5,10], calendar.month_name[1:4], color='#00ff00',rotation=30)
plt.xlabel('x')
plt.ylabel('y')
plt.title('x-y')
plt.plot(x,y)
plt.show()

在这里插入图片描述

set_limits

'''
    ★plt.xlim(xmin, xmax), 函数功能:设置x轴的数值显示范围。
    ★plt.ylim(ymin, ymax), 函数功能:设置y轴的数值显示范围。
'''
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-np.pi,np.pi,30,endpoint=True)
c,s = 2*np.cos(x), np.sin(x)
# fig = plt.figure()
# ax = fig.add_axes([0.2,0.2,1,1])
plt.plot(x,c,'b',linewidth=2.5,linestyle='-')
plt.plot(x,s,'g',linewidth=2.5,linestyle='-')

plt.xlim(x.min()*0.7, x.max()*0.7)
plt.ylim(c.min()*1.5, c.max()*1.5)

plt.legend(["2cosx", "sinx"])

plt.show()

在这里插入图片描述

图例legend

'''
    ★Let's add a legend in the upper left corner. This only requires adding the keyword
    argument label (that will be used in the legend box) to the plot commands.

    ★legend entry
    ★A legend is made up of one or more legend entries.
    ★An entry is made up of exactly one key and one label.

    ★legend key
    ★The colored/patterned marker to the left of each legend label.

    ★legend label
    ★The text which describes the handle represented by the key.

    ★legend handle
    ★The original object which is used to generate an appropriate entry in the legend.
    ★(1)设置图列位置
    plt.legend(loc='upper center')

    0: ‘best'
    1: ‘upper right'
    2: ‘upper left'
    3: ‘lower left'
    4: ‘lower right'
    5: ‘right'
    6: ‘center left'
    7: ‘center right'
    8: ‘lower center'
    9: ‘upper center'
    10: ‘center'
    ★(2)设置图例字体大小
    fontsize : int or float or {‘xx-small’, ‘x-small’, ‘small’, ‘medium’, ‘large’, ‘x-large’, ‘xx-large’}
    ★(3)设置图例边框及背景
    plt.legend(loc='best',frameon=False) #去掉图例边框
    plt.legend(loc='best',edgecolor='blue') #设置图例边框颜色
    plt.legend(loc='best',facecolor='blue') #设置图例背景颜色,若无边框,参数无效
    设置图例标题
    legend = plt.legend(["CH", "US"], title='China VS Us')
    ★(5)设置图例名字及对应关系
    legend = plt.legend([p1, p2], ["CH", "US"])
'''

#导入包
import numpy as np
import matplotlib.pyplot as plt
#加载数据
# train_x = np.linspace(-1, 1, 100)
# train_y_1 = 2*train_x + np.random.rand(*train_x.shape)*0.3
# train_y_2 = train_x**2+np.random.randn(*train_x.shape)*0.3
# #作图
# p1 = plt.scatter(train_x, train_y_1, c='red', marker='v' )
# p2= plt.scatter(train_x, train_y_2, c='blue', marker='o' )
# #修饰
# legend = plt.legend([p1, p2], ["CH", "US"], facecolor='blue')
# #显示
# plt.show()




import numpy as np
import matplotlib.pyplot as plt

X = np.linspace(-np.pi, np.pi, 20, endpoint=True)
C,S = np.cos(X), np.sin(X)

C_plot_list=plt.plot(X, 1.5*C, color="r", linewidth=2.5, linestyle="-")
#注:C_plot_list是一个列表

C_plot,=plt.plot(X, C, color="g", linewidth=2.5, linestyle="-")
S_plot,=plt.plot(X, S, color="b", linewidth=2.5, linestyle="-")
#要将长度为1的元组或列表中元素提取出来可以用,简化赋值操作

print(type(C_plot_list),type(C_plot))

legend = plt.legend([C_plot, S_plot], ["CH", "US"], facecolor='#005588')

plt.show()

在这里插入图片描述

指定可视区域

'''
★The axis() command in the example takes a list of [xmin, xmax, ymin, ymax] and specifies
    the viewport of the axes.
★axis()命令接收[xmin,xmax,ymin,ymax]的列表,并指定轴域的可视区域。
'''
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-np.pi,np.pi,256,endpoint=True)
c,s = np.cos(x), np.sin(x)
fig = plt.figure()
plt.plot(x,c,'b',linewidth=2.5,linestyle='-')
plt.plot(x,s,'g',linewidth=2.5,linestyle='-')

plt.axis([-4,4,-1,1])

plt.show()

在这里插入图片描述

设置刻度标签

'''
*****************  Setting tick labels  *****************
    ★Ticks are now properly placed but their label is not very explicit. We could guess that
    3.142 is π but it would be better to make it explicit. When we set tick values, we can
    also

    ★字符串前边的r代表是原始字符串,也就是里边的内容不需要转义,
    ★这个一般在正则表达式的时候用,而这里是laText的用法,
    ★在python中使用laText,需要在文本的前后加上$符号,
    ★然后就是laText的文本了,当输入了以上内容,matplotlib会自动解析的,
    ★\pi代表的就是π。
'''
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C,S = np.cos(X), np.sin(X)
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)
# plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi])
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],['$-\pi$', '$-\pi/2$', '$0$', '$+\pi/2$', '$+\pi$'])
# plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
plt.yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$'])
plt.show()

在这里插入图片描述

moving spines

'''
*****************  Moving spines  *****************
    ★脊梁:包围图表的线条
    ★Spines are the lines connecting the axis tick marks and noting the boundaries of the data
    area. They can be placed at arbitrary positions and until now, they were on the border of
    the axis. We'll change that since we want to have them in the middle. Since there are four
    of them (top/bottom/left/right), we'll discard the top and right by setting their color to
    none and we'll move the bottom and left ones to coordinate 0 in data space coordinates.
    ★如果要移动坐标到中心点,那么我们可以移动其中的两条边,并隐藏两条边即可
    ★ax.xaxis.set_ticks_position(‘bottom’)
    ★ax.yaxis.set_ticks_position(‘left’)
    ★ax.spines[‘right’].set_color(‘none’)
    ★ax.spines[‘top’].set_color(‘none’)

    ★接下来就是指定x轴以及y轴的绑定:
    ★ax.spines[‘bottom’].set_position((‘data’, 0))
    ★ax.spines[‘left’].set_position((‘data’, 0))
    ★结果是将x,y轴绑定到特定位置,即坐标轴的交点是(0, 0),

    ★如果两条线的交点要设置为(1,0)
    ★ax.spines[‘bottom’].set_position((‘data’, 0))
    ★ax.spines[‘left’].set_position((‘data’, 1))
'''
import numpy as np
import matplotlib.pyplot as plt
X = np.linspace(-np.pi, np.pi, 256, endpoint=True)
C,S = np.cos(X), np.sin(X)
fig = plt.figure()
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
plt.yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$'])
#上下比较
fig = plt.figure()
plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
plt.yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$'])

ax = plt.gca()#获得当前的Axes对象或图
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data',0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))

plt.show()

在这里插入图片描述

显示中文

'''
*****************  正常显示中文  *****************
    ★plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
    ★'SimHei':中文黑体;'Kaiti':中文楷体;'LiSu':中文隶书;
    ★'FangSong':中文仿宋;'YouYuan':中文幼圆;'STSong':华文宋体;
    ★plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
    ----------------------------------------------------------------
    import numpy as np
    import matplotlib.pyplot as plt
    X = np.linspace(-np.pi, np.pi, 20, endpoint=True)
    C,S = np.cos(X), np.sin(X)
    fig = plt.figure()
    plot_C,=plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
    plot_S,=plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
    plt.xlim(X.min()*1.1, X.max()*1.1)
    plt.ylim(C.min()*1.1, C.max()*1.1)
    plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
    plt.yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$'])
    plt.title('正弦-余弦曲线')
    legend = plt.legend([plot_C, plot_S], ["余弦", "正弦"], facecolor='g')
    plt.show()
'''
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
X = np.linspace(-np.pi, np.pi, 20, endpoint=True)
C,S = np.cos(X), np.sin(X)
fig = plt.figure()
plot_C,=plt.plot(X, C, color="blue", linewidth=2.5, linestyle="-")
plot_S,=plt.plot(X, S, color="red", linewidth=2.5, linestyle="-")
plt.xlim(X.min()*1.1, X.max()*1.1)
plt.ylim(C.min()*1.1, C.max()*1.1)
plt.xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi],[r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$'])
plt.yticks([-1, 0, +1],[r'$-1$', r'$0$', r'$+1$'])
plt.title('正弦-余弦曲线')
legend = plt.legend([plot_C, plot_S], ["余弦", "正弦"], facecolor='g')
plt.show()

在这里插入图片描述

插入文字

'''
*****************************************  CH5  *****************************************
*****************************************  CH5  *****************************************

*****************  插入文字  *****************
    ★The text() command can be used to add text in an arbitrary location, and the xlabel(),
    ylabel() and title() are used to add text in the indicated locations

    ★plt.text(x, y, s, fontsize, verticalalignment,horizontalalignment,rotation , **kwargs)
    ★x,y:标签添加的位置,注释文本内容所在位置的横/纵坐标,默认是根据坐标轴的数据来度量的,
    ★是绝对值,也就是说图中点所在位置的对应的值,特别的,如果你要变换坐标系的话,
    ★要用到transform=ax.transAxes参数。
    ★s:标签的符号,字符串格式,比如你想加个“我爱python”,更多的是你标注跟数据有关的主体。
    ★fontsize:加标签字体大小,取整数。
    ★verticalalignment:垂直对齐方式 ,可选 ‘center’ ,‘top’ , ‘bottom’,‘baseline’ 等
    ★horizontalalignment:水平对齐方式 ,可以填 ‘center’ , ‘right’ ,‘left’ 等
    ★rotation:标签的旋转角度,以逆时针计算,取整
    ★family :设置字体
    ★style: 设置字体的风格
    ★weight:设置字体的粗细
    ★wrap:要不要换行
    ★bbox:给字体添加框, 如 bbox=dict(facecolor=‘red’, alpha=0.5) 等。
    ★string:注释文本内容
    ★color:注释文本内容的字体颜色
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.05, 10, 1000)
y = np.sin(x)
plt.plot(x, y, ls="-.", lw=2, c="c", label="plot figure")
plt.legend()

plt.text(3.10, 0.09, "y=sin(x)",fontsize=25 ,weight="bold", color="b")

plt.show()
-----------------------------------------------------------------------------------
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
plt.axis([0, 10, 0, 10])
t = "This is a really long string that I'd rather have wrapped so that it"\
" doesn't go outside of the figure, but if it's long enough it will go"\
" off the top or bottom!"

plt.text(4, 1, t, ha='center', rotation=15, wrap=True)
plt.text(0, 10, t, ha='left', rotation=-30, wrap=False)
plt.text(7, 7, 123456, ha='right', rotation=-15, wrap=True)
plt.show()
-----------------------------------------------------------------------------------------
完整代码
#加载包
import numpy as np
import matplotlib.pyplot as plt
  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值