python之matplotlib应用

来源:互联网 发布:盲源分离理论与算法 编辑:程序博客网 时间:2024/06/07 09:50
  1. 画简单图
  2. 添加标题,图例,x,y轴的名字
  3. 创建子图
  4. 在子图中展示图片数据—uint8转化

1.画简单图

import numpy as npimport matplotlib.pyplot as pltx = np.arange(0, 3 * np.pi, 0.1)y = np.sin(x)# 使用matplotlib画图plt.plot(x, y)plt.show()  # 这个必须要有,图才会显示

2.添加标题,图例,x,y轴的名字

import numpy as npimport matplotlib.pyplot as pltx = np.arange(0,3*np.pi , 0.2)y_sin = np.sin(x)y_cos = np.cos(x)plt.plot(x,y_sin)plt.plot(x,y_cos)plt.xlabel('the name of x axis')  #x 轴的名字plt.ylabel(' the name of y axis')  #y轴的名字plt.title('Sine and Cosine')  #加一个标题plt.legend(['Sine','Cosine'])  #加一个图例plt.show()

3.创建子图

import numpy as npimport matplotlib.pyplot as pltx = np.arange(0,3*np.pi,0.1)y_sin = np.sin(x)y_cos = np.cos(x)#创建一个子图方格,高2,宽1plt.subplot(2,1,1) #把第一个子图设置为激活状态plt.plot(x,y_sin)plt.title('Sine')#把第二个子图设置为激活状态plt.subplot(2,1,2)plt.plot(x,y_cos)plt.title('Cosine')plt.show()

4.在子图中展示图片

from scipy.misc import imread,imresizeimg = imread('/Users/huanghuaixian/desktop/图片/风景.png')img_tinted = img*[1,0.95,0.4]#把原图展示出来plt.subplot(1,2,1)plt.imshow(img)#再看一下把颜色通道改了之后的图plt.subplot(1,2,2)plt.imshow(img_tinted)plt.show()

这里的颜色通道更改完之后,没有把它变成uint8格式,会出现奇怪的样子
这里写图片描述

plt.imshow(np.uint8(img_tinted)) #因此需要把转化后的变成uint8格式

这样就好很多了
这里写图片描述

5.嵌套多个子图,设置中文字体

import matplotlib.pyplot as pltfrom matplotlib.font_manager import FontPropertiesfont = FontProperties(fname = '/Users/huanghuaixian/a_little_time/Arial Unicode.ttf',size = 14) #mac里有内置的字体,windows也可以网上下载字体fig = plt.figure()fig.set(alpha = 0.2)fig.set_size_inches(18, 7)  #设置整张图片的大小plt.subplot2grid((2,3),(0,0))data_train.Survived.value_counts().plot(kind =' bar ')plt.title(u'获救情况(1为获救)', fontproperties=font)plt.ylabel(u'人数', fontproperties=font)plt.subplot2grid((2,3),(0,1))data_train.Pclass.value_counts().plot(kind =' bar ')plt.title(u'获救情况(1为获救)', fontproperties=font)plt.ylabel(u'人数', fontproperties=font)plt.subplot2grid((2,3),(0,2))plt.scatter(data_train.Survived,data_train.Age)plt.grid(b = True, which = 'major', axis = 'y')plt.ylabel(u'年龄', fontproperties=font)plt.title(u'按年龄看获救情况', fontproperties=font)plt.subplot2grid((2,3),(1,0),colspan=2) #占据两个空间data_train.Age[data_train.Pclass==1].plot(kind = 'kde')data_train.Age[data_train.Pclass==2].plot(kind = 'kde')data_train.Age[data_train.Pclass==3].plot(kind = 'kde')plt.title(u'不同仓位的乘客密度分布', fontproperties=font)plt.xlabel(u'乘客年龄', fontproperties=font)plt.ylabel(u'密度', fontproperties=font)plt.legend((1,2,3),loc='best')plt.subplot2grid((2,3),(1,2))data_train.Embarked.value_counts().plot(kind='bar')plt.title(u"各登船口岸上船人数", fontproperties=font)plt.ylabel(u"人数", fontproperties=font)  plt.show()

fontproperties=font是对中文的设置,每一个有中文的地方都要用这个。

这里写图片描述
还是直接用英文最好

原创粉丝点击