Matplotlib做基本图"/>
Matplotlib做基本图
Matplotlib做基本图的编码。
import random import matplotlib.pyplot as plt import matplotlib as mpl from matplotlib import style import csv import numpy as np import matplotlib.mlab as mlab from mpl_toolkits.basemap import Basemap from mpl_toolkits.mplot3d import axes3d from mpl_toolkits.mplot3d import Axes3D import matplotlib.dates as mdates# 画线 x = [1,2,3] y = [5,7,4] x2 = [1,2,3] y2 = [10,14,12] plt.plot(x, y, label='First Line')#此处的label为图例,默认在左上角 plt.plot(x2, y2, label='Second Line') plt.xlabel('Plot Number')#x坐标轴名称 plt.ylabel('Important var')#y坐标轴名称 plt.title('Interesting Graph\nCheck it out')#图名,当一张图时或出现在居中位置 plt.legend()#放置图例的容器,如果不写就无法显示图例,当然图例也可以在这个函数中写,具体见下个例子 plt.show()#显示图形,缺少该句则无法显示 #条形图 fig = plt.figure(1) bar1=plt.bar([1,3,5,7,9],[5,2,7,8,2]) bar2=plt.bar([2,4,6,8,10],[8,6,2,5,6], color='g') plt.legend([bar1,bar2],['Example one','Example one'],loc='upper right')#图例,有多条图线或者直方图时会显示,loc表示位置,一般设置为“upper right” plt.xlabel('bar number') plt.ylabel('bar height') plt.title('Epic Graph\nAnother Line! Whoa') plt.show() # #直方图 population_ages = [22,55,62,45,21,22,34,42,42,4,99,102,110,120,121,122,130,111,115,112,80,75,65,54,44,43,42,48]#具体的数据 bins = [0,10,20,30,40,50,60,70,80,90,100,110,120,130]#范围,分组 plt.hist(population_ages, bins, normed=1,histtype='bar', rwidth=0.8,label="age group") #bins为直方图的柱数,population_ages位置上为arr,为需要计算直方图的数组,normed是否将得到的直方图向量归一化,默认为0,histtype为直方图类型,有bar、barstacked、step、stepfilled #facecolor为直方图颜色,常见的有r、g等, plt.xlabel('age group') plt.ylabel('bumber') plt.title('Interesting Graph\nCheck it out') plt.legend() plt.show() #散点图 x = [1,2,3,4,5,6,7,8] y = [5,2,4,2,1,4,5,2] plt.scatter(x,y, label='skitscat', c='r', s=25, marker="o",lw=5) #x,y为输入的数据,x与y的长度一致,label为图例,c为颜色,b-blue c-cyan g-green k-black r-red y-yellow,可以为列表,marker为形状,“o",".",",","v","^",">","<" #lw为linewidth,表示线的宽度 plt.xlabel('x') plt.ylabel('y') plt.title('Interesting Graph\nCheck it out') plt.legend() plt.show() # 堆叠图 days = [1,2,3,4,5] sleeping = [7,8,6,11,7] eating = [2,3,4,3,2] working = [7,8,7,2,2] playing = [8,5,7,8,13] plt.stackplot(days, sleeping,eating,working,playing,colors=['m','c','r','k'])#sleeping/eating/working/playing对应列和为24 plt.xlabel('x') plt.ylabel('y') plt.legend(['sleeping','eating','working','playing'],loc='lower right')#显示图例 plt.title('Interesting Graph\nCheck it out') plt.savefig('1.png')#保存图片 plt.show() #饼图 slices = [7,2,2,13] activities = ['sleeping','eating','working','playing'] cols = ['c','m','r','b'] plt.pie(slices,#视为每一块的比例 labels=activities,#每一块饼图外侧显示的说明文字,与slices相对应 colors=cols,#每一块对应的颜色 startangle=90,#起始绘制角度,默认图是从x轴正方向逆时针画起,如设定=90则从y轴正方向画起 shadow= True,#是否需要阴影 explode=(0,0.1,0,0),#每一块离开中心的距离 radius=1,#绘制饼图的半径 autopct='%1.1f%%')#控制饼图内百分比设置,%m.nf指小数点前后位数 plt.legend(['sleeping','eating','working','playing'])#加上图例 plt.title('Interesting Graph\nCheck it out') plt.show() #从文件中加载数据 #使用csv模块 # 1,2 # 3,4 # 5,6 x=[] y=[] with open(r'D:\pythonplaces\DeepLearning\plt\dataset.txt','r') as csvfile:plots = csv.reader(csvfile, delimiter=' ')#用CSV模块需要txt文件里的数据用逗号隔开,delimiter为分隔符,可以是',',也可以是' '空格 for row in plots:#row表示每一行,自动按行分割文件 x.append(int(row[0]))y.append(int(row[1])) plt.plot(x,y, label='Loaded from file!') plt.xlabel('x') plt.ylabel('y') plt.title('Interesting Graph\nCheck it out') plt.legend() plt.show() #使用numpy模块 x, y = np.loadtxt(r'D:\pythonplaces\DeepLearning\plt\dataset.txt', delimiter=' ', unpack=True)#分隔符为空格 plt.plot(x,y, label='Loaded from file!') plt.xlabel('x') plt.ylabel('y') plt.title('Interesting Graph\nCheck it out') plt.legend() plt.show() #Basemap地理绘图 m = Basemap(projection='mill', llcrnrlat = -90, llcrnrlon = -180, urcrnrlat = 90, urcrnrlon = 180, resolution='l') #西经和南纬是负值,北纬和东经是正值 # llcrnrlat - 左下角的纬度 # llcrnrlon - 左下角的经度 # urcrnrlat - 右上角的纬度 # urcrnrlon - 右上角的经度 #分辨率选项为c-粗糙,l-低,h-高,f-完整 m.drawcoastlines()#画出海岸线 m.drawcountries(linewidth=2)#画出国家,并用线宽为2的线条生成分界线 # m.drawstates(color='b')#蓝色线条画出州 # m.drawcounties(color='darkred') #m.etopo()#画出地形图 #m.bluemarble()#大理石版本的地形图 plt.savefig('map.png') plt.title('Basemap Tutorial') plt.show() #如何绘制单个坐标,以及如何在地理区域中连接这些坐标 xs=[] ys=[] m = Basemap(projection='mill', llcrnrlat = 25, llcrnrlon = -130, urcrnrlat = 50, urcrnrlon = -60, resolution='l') m.drawcoastlines() m.drawcountries(linewidth=2) m.drawstates(color='b') NYClat=40.7127 NYClon=-74.0059 xpt,ypt=m(NYClon,NYClat)#注意经纬度和坐标的转换 xs.append(xpt) ys.append(ypt) m.plot(xpt,ypt,'c*',markersize=15) LAlat, LAlon = 34.05, -118.25 xpt, ypt = m(LAlon, LAlat) xpt,ypt=m(LAlon,LAlat) xs.append(xpt) ys.append(ypt) m.plot(xpt, ypt, 'g^', markersize=15) m.plot(xs, ys, color='r', linewidth=3, label='Flight 98')#画直线连接 m.drawgreatcircle(NYClon, NYClat, LAlon, LAlat, color='c', linewidth=3, label='Arc')#画弧链接,可以画多条,多个坐标 plt.legend(loc=4) plt.title('Basemap Tutorial') plt.show() #3D绘图 style.use('ggplot')fig = plt.figure() ax1 = fig.add_subplot(111, projection='3d')#做出一个三维柱状图 #散点数据集 x = [1,2,3,4,5,6,7,8,9,10] y = [5,6,7,8,2,5,6,3,7,2] z = [1,2,6,3,2,7,3,3,7,2]x2 = [-1,-2,-3,-4,-5,-6,-7,-8,-9,-10] y2 = [-5,-6,-7,-8,-2,-5,-6,-3,-7,-2] z2 = [1,2,6,3,2,7,3,3,7,2]ax1.scatter(x, y, z, c='g', marker='o')#第一个数据集上画散点图 ax1.scatter(x2, y2, z2, c ='r', marker='o')#第二个数据集上画散点图 #标出坐标轴名称 ax1.set_xlabel('x axis') ax1.set_ylabel('y axis') ax1.set_zlabel('z axis') #显示图形 plt.show() #meshgrid函数是将一维数组扩充为矩阵 #3D线框图 style.use('ggplot')fig = plt.figure() ax1 = fig.add_subplot(111, projection='3d')x, y, z = axes3d.get_test_data()print(axes3d.__file__) ax1.plot_wireframe(x,y,z, rstride = 3, cstride = 3)ax1.set_xlabel('x axis') ax1.set_ylabel('y axis') ax1.set_zlabel('z axis')plt.show() #空间曲面的画法 fig = plt.figure() x = np.linspace(-10, 10, 101)#范围从-10到10,一共分101个点 y = x x, y = np.meshgrid(x, y)#扩展将一维矩阵扩展成为坐标矩阵 z = x ** 2 + y ** 2 ax = fig.add_subplot(111, projection='3d') ax.plot_wireframe(x, y, z)#线框图 plt.show() #半径为1的球 t = np.linspace(0, np.pi*2, 100) s = np.linspace(0, np.pi, 100) t, s = np.meshgrid(t, s)#三维做图先生成一个二维平面 x = np.cos(t) * np.sin(s) y = np.sin(t) * np.sin(s) z = np.cos(s) ax = plt.subplot(111, projection='3d') ax.plot_wireframe(x, y, z) plt.show() #画出带横纵坐标文本的条形图 labels= ["China","India","USA","Indonesia","Brasil","Pakistan","Nigeria","Bangladesh","Russian","Japan"] quants= [1405372834,1304200000,322760000,257740000,205290000,192400000,182310000,164620000,146350000,126820000] ind = np.linspace(0,9,10)#0到10之间分9段 print(ind) fig = plt.figure(1, figsize=(12,6)) ax= fig.add_subplot(111) ax.bar(ind,quants,0.5,color='green') ax.set_xticks(ind)#刻度 ax.set_xticklabels(labels)#横坐标设置文本 ax.set_xlabel('Country') ax.set_ylabel('Population') # ax.set_title('Top 10 countries of the population', bbox={'facecolor':'0.5', 'pad':2}) ax.set_title('Top 10 countries of the population') plt.show() #服从泊松分布的网格直方图 x=np.random.poisson(lam=5,size=10000)#lam=拿麻它,size为k pillar=15 a=plt.hist(x,bins=pillar,normed=True,range=[0,pillar],color='g') plt.grid() # plt.show() #随机分布的直方图 x=np.random.rand(10000) t=np.arange(len(x)) t=10000 a=np.zeros(1000) for i in range(t):a+=np.random.uniform(-5,5,1000) a/=t plt.hist(a,bins=100,color='g',alpha=0.5,normed=True)#alpha表示透明度 plt.grid() plt.show() #正弦函数曲线 x=np.arange(0,10,0.1) y=np.sin(x) plt.bar(x,y,width=0.06,linewidth=0.2) plt.plot(x,y,'r--',linewidth=2) plt.title('Sin') plt.xticks(rotation=-60) plt.xlabel('x') plt.ylabel('y') plt.grid() # plt.show() #画正态分布 mu, sigma , num_bins = 0, 1, 50 x = mu + sigma * np.random.randn(1000000)# 正态分布的数据 n, bins, patches = plt.hist(x, num_bins, normed=True, facecolor = 'blue', alpha = 0.5)# 拟合曲线 y = mlab.normpdf(bins, mu, sigma) plt.plot(bins, y, 'r--') plt.xlabel('Expectation') plt.ylabel('Probability') plt.title('histogram of normal distribution: $\mu = 0$, $\sigma=1$') plt.subplots_adjust(left = 0.15) # plt.show() #3D柱状图 mpl.rcParams['font.size'] = 10 fig = plt.figure() ax = fig.add_subplot(111, projection='3d') for z in [2015, 2016, 2017]:xs = range(1,13)ys = 1000 * np.random.rand(12)#随机颜色 #color =plt.cm.Set2(random.choice(range(plt.cm.Set2.N))) # 自定义颜色及透明度 color = ((1.0, 0.0, 0.0,0.2), #color有三行则控制三种颜色 (0.0, 1.0, 0.0,0.2), (0.0, 0.0, 1.0,0.2))ax.bar(xs, ys, zs=z, zdir='y', color=color, alpha=0.8)ax.xaxis.set_major_locator(mpl.ticker.FixedLocator(xs)) ax.yaxis.set_major_locator(mpl.ticker.FixedLocator(ys))ax.set_xlabel('Month') ax.set_ylabel('Year') ax.set_zlabel('Sales Net') plt.show() #画多个图 fig=plt.figure() ax1=fig.add_subplot(2,2,1)#添加子图 ax1.hist(np.random.randn(100),bins=10,color='r',alpha=0.3) plt.title("first") plt.legend(['first'],loc='upper right') ax2=fig.add_subplot(2,2,2) ax2.scatter(np.arange(30),np.arange(30)+3*np.random.randn(30)) plt.title("second") ax3=fig.add_subplot(2,2,3) plt.plot(np.random.randn(50).cumsum(),'g*') ax4=fig.add_subplot(2,2,4) plt.show() #横向条形图 data = [5, 20, 15, 25, 10] plt.barh(range(len(data)), data,color=['r','g','b']) plt.show() #画两个在一块的柱状图 plt.figure(figsize=(9, 6)) n = 8 X = np.arange(n) + 1 #表示横坐标范围 print(X) # X是1,2,3,4,5,6,7,8,柱的个数 # numpy.random.uniform(low=0.0, high=1.0, size=None), normal # uniform均匀分布的随机数,normal是正态分布的随机数,0.5-1均匀分布的数,一共有n个 Y1 = np.random.uniform(0.5, 1.0, n) Y2 = np.random.uniform(0.5, 1.0, n) plt.plot(X,Y1,color='r') plt.bar(X, Y1, width=0.35, facecolor='lightskyblue', edgecolor='white',label='first') # width:柱的宽度 plt.plot(X+0.35,Y2,color='b') plt.bar(X + 0.35, Y2, width=0.35, facecolor='yellowgreen', edgecolor='white',label='second')#位置紧靠着第一个柱状图 # 水平柱状图plt.barh,属性中宽度width变成了高度height # 打两组数据时用+ # facecolor柱状图里填充的颜色 # edgecolor是边框的颜色 # 想把一组数据打到下边,在数据前使用负号 # plt.bar(X, -Y2, width=width, facecolor='#ff9999', edgecolor='white') # 给图加text for x, y in zip(X, Y1):plt.text(x , y + 0.05, '%.2f' % y, ha='center', va='bottom')for x, y in zip(X, Y2):plt.text(x + 0.35, y + 0.05, '%.2f' % y, ha='center', va='bottom') plt.legend() plt.ylim(0, +1.25)#设置y轴的刻度范围 plt.show() #做三维散点图 data = np.random.randint(0, 255, size=[40, 40, 40])#生产数据,40行40列每行5个数据 x, y, z = data[0], data[1], data[2] print(x.shape) ax = plt.subplot(111, projection='3d') # 创建一个三维的绘图工程 # 将数据点分成三部分画,在颜色上有区分度 ax.scatter(x[:10], y[:10], z[:10], c='y') # 绘制数据点,依次绘制 ax.scatter(x[10:20], y[10:20], z[10:20], c='r') ax.scatter(x[30:40], y[30:40], z[30:40], c='g')ax.set_zlabel('Z') # 坐标轴 ax.set_ylabel('Y') ax.set_xlabel('X') plt.show() #三维线形图 x = np.linspace(-6 * np.pi, 6 * np.pi, 1000) y = np.sin(x) z = np.cos(x) # 创建 3D 图形对象 fig = plt.figure() ax = Axes3D(fig) # 绘制线型图 ax.plot(x, y, z) plt.show() # 显示图 # 三维柱状图 fig = plt.figure() ax = Axes3D(fig) # 生成数据并绘图 z = [2015,2016,2017,2018,2019,2020] for i in z:x = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10,11,12]#y = abs(np.random.normal(1, 13, 13)) y=abs(np.random.normal(1,13,13))ax.bar(x, y, i, zdir='y', color=['r', 'g', 'b', 'y'])#一般以y为参考 ax.set_xlabel('Y') # 坐标轴名称可以进行修改,一般可用与纵向比较 ax.set_ylabel('X') ax.set_zlabel('Z') plt.show()
更多推荐
Matplotlib做基本图
发布评论