画坐标系沉淀再出发:用python画各种图表
一、前言
最近需要用python来做一些统计和画图,因此做一些笔记。
二、python画各种图表
2.1、使用turtle来画图
1 import turtle as t #turtle库是python的内部库,直接import使用即可 2 import time 3 4 def draw_diamond(turt): 5 for i in range(1,3): 6 turt.forward(100) #向前走100步 7 turt.right(45) #海龟头向右转45度 8 turt.forward(100) #继续向前走100步 9 turt.right(135) #海龟头再向右转135度 10 11 12 def draw_art(): 13 window = t.Screen() #创建画布 14 window.bgcolor("green") #设置画布颜色 15 brad = t.Turtle() #创建一个Turtle的实例 16 brad.shape('turtle') #形状是一个海归turtle,也可以是圆圈circle,箭头(默认)等等 17 18 brad.color("red") #海龟的颜色是红色red,橙色orange等 19 brad.speed('fast') #海龟画图的速度是快速fast,或者slow等 20 21 for i in range(1,37): #循环36次 22 draw_diamond(brad) #海龟画一个形状/花瓣,也就是菱形 23 brad.right(10) #后海龟头向右旋转10度 24 25 brad.right(90) #当图形画完一圈后,把海龟头向右转90度 26 brad.forward(300) #画一根长线/海龟往前走300步 27 28 window.exitonclick() #点击屏幕退出 29 30 draw_art() #调用函数开始画图 31 32 33 34 t.color("red", "yellow") 35 t.speed(10) 36 t.begin_fill() 37 for _ in range(50): 38 t.forward(200) 39 t.left(170) 40 end_fill() 41 time.sleep(1)
2.2、画坐标系
1 import sys 2 import math 3 import random 4 import matplotlib.pyplot as plt 5 import pylab as pl 6 import numpy as np 7 8 pl.mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体 9 pl.mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 10 11 x = range(10) # 横轴的数据 12 y = [i*i for i in x] # 纵轴的数据 13 y1 = [i*i+123 for i in x] # 纵轴的数据 14 pl.title('title zyr') 15 pl.plot(x, y, '1m:', label=u'compare') # 加上label参数添加图例 16 pl.plot(x, y1, '>r--', label=u'set other') # 加上label参数添加图例 17 pl.xlabel(u"横轴的数据") 18 pl.ylabel(u"纵轴的数据") 19 pl.legend() # 让图例生效 20 pl.show() # 显示绘制出的图
import sys import math import random import matplotlib.pyplot as plt import pylab as pl import numpy as np pl.mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体 pl.mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 x = list(range(10))+[100] y = [i*i for i in x] pl.plot(x, y, 'ob-', label=u'y=x^2') pl.xlim(-1, 11) # 限定横轴的范围 pl.ylim(-1, 110) # 限定纵轴的范围 pl.show() # 显示绘制出的图
1 颜色(color 简写为 c): 2 # 蓝色: 'b' (blue) 3 # 绿色: 'g' (green) 4 # 红色: 'r' (red) 5 # 蓝绿色(墨绿色): 'c' (cyan) 6 # 红紫色(洋红): 'm' (magenta) 7 # 黄色: 'y' (yellow) 8 # 黑色: 'k' (black) 9 # 白色: 'w' (white) 10 11 # 线型(linestyle 简写为 ls): 12 # 实线: '-' 13 # 虚线: '--' 14 # 虚点线: '-.' 15 # 点线: ':' 16 # 点: '.' 17 18 # 点型(标记marker): 19 # 像素: ',' 20 # 圆形: 'o' 21 # 上三角: '^' 22 # 下三角: 'v' 23 # 左三角: '<' 24 # 右三角: '>' 25 # 方形: 's' 26 # 加号: '+' 27 # 叉形: 'x' 28 # 棱形: 'D' 29 # 细棱形: 'd' 30 # 三脚架朝下: '1'(像'丫') 31 # 三脚架朝上: '2' 32 # 三脚架朝左: '3' 33 # 三脚架朝右: '4' 34 # 六角形: 'h' 35 # 旋转六角形: 'H' 36 # 五角形: 'p' 37 # 垂直线: '|' 38 # 水平线: '_'
2.3、柱状图
1 import numpy as np 2 import matplotlib.animation as animation 3 import time 4 5 mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体 6 mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 7 8 source_data = {'mock_verify': 369, 'mock_notify': 192, 'mock_sale': 517} # 设置原始数据 9 10 for a, b in source_data.items(): 11 plt.text(a, b + 0.05, '%.0f' % b, ha='center', va='bottom', fontsize=11) # ha 文字指定在柱体中间, va指定文字位置 fontsize指定文字体大小 12 13 # 设置X轴Y轴数据,两者都可以是list或者tuple 14 x_axis = tuple(source_data.keys()) 15 y_axis = tuple(source_data.values()) 16 plt.bar(x_axis, y_axis, color='rg') # 如果不指定color,所有的柱体都会是一个颜色 17 18 plt.xlabel(u"渠道名") # 指定x轴描述信息 19 plt.ylabel(u"访问量") # 指定y轴描述信息 20 plt.title("渠道访问量统计表") # 指定图表描述信息 21 plt.ylim(0, 600) # 指定Y轴的高度 22 # plt.savefig('{}.png'.format(time.strftime('%Y%m%d%H%M%S'))) # 保存为图片 23 plt.show()
2.4、扇形图
1 import matplotlib.pyplot as plt 2 import time 3 from pylab import mpl 4 import numpy as np 5 import matplotlib.animation as animation 6 import time 7 8 mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体 9 mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 10 11 data = {'8516464': 106, '8085460': 704, '7593813': 491, '8709362': 24, '8707829': 6, '8684658': 23, '8679301': 11, 12 '8665923': 29, '8660909': 23, '8652968': 31, '8631727': 31, '8622935': 24, '8620593': 18, '8521737': 33, 13 '8605441': 49, '8495205': 82, '8477276': 57,'8474489': 71, '8456502': 50, '8446529': 68, '8433830': 136, 14 '8254158': 103, '8176029': 88, '8081724': 58, '7922592': 185, '7850099': 62,'7617723': 61, '7615562': 90, 15 '7615052': 57, '7604151': 102, '7511294': 59,'6951654': 27, '6946388': 142, '6945373': 159, '6937716': 347, 16 '7460176': 64, '7246377': 87, '7240621': 145, '7204707': 645, '7028401': 671} 17 source_data = sorted(data.items(), key=lambda x: x[1], reverse=True) 18 print(source_data) 19 labels = [source_data[i][0][:4] for i in range(len(source_data))] # 设置标签 20 fracs = [source_data[i][1] for i in range(len(source_data))] 21 explode = [x * 0.01 for x in range(len(source_data))] # 与labels一一对应,数值越大离中心区越远 22 plt.axes(aspect=1) # 设置X轴 Y轴比例 23 # labeldistance标签离中心距离 pctdistance百分百数据离中心区距离 autopct 百分比的格式 shadow阴影 24 plt.pie(x=fracs, labels=labels, explode=explode, autopct='%3.1f %%', 25 shadow=False, labeldistance=1.1, startangle=0, pctdistance=0.8, center=(-1, 0)) 26 # 控制位置:bbox_to_anchor数组中,前者控制左右移动,后者控制上下。ncol控制 图例所列的列数。默认值为1。fancybox 圆边 27 plt.legend(loc=7, bbox_to_anchor=(1.2, 0.80), ncol=3, fancybox=True, shadow=True, fontsize=8) 28 plt.show()
2.5、动图
1 import matplotlib.pyplot as plt 2 import time 3 from pylab import mpl 4 import numpy as np 5 import matplotlib.animation as animation 6 import time 7 8 mpl.rcParams['font.sans-serif'] = ['FangSong'] # 指定默认字体 9 mpl.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题 10 11 12 # Fixing random state for reproducibility 13 np.random.seed(196) 14 # 初始数据绘图 15 dis = np.zeros(40) 16 dis2 = dis 17 fig, ax = plt.subplots() 18 line, = ax.plot(dis) 19 ax.set_ylim(-1, 1) 20 plt.grid(True) 21 ax.set_ylabel("distance: m") 22 ax.set_xlabel("time") 23 24 def update(frame): 25 global dis 26 global dis2 27 global line 28 # 读入模拟 29 a = np.random.rand() * 2 - 1 30 time.sleep(np.random.rand() / 10) 31 # 绘图数据生成 32 dis[0:-1] = dis2[1:] 33 dis[-1] = a 34 dis2 = dis 35 # 绘图 36 line.set_ydata(dis) 37 # 颜色设置 38 plt.setp(line, 'color', 'c', 'linewidth', 2.0) 39 ani = animation.FuncAnimation(fig, update, frames=None, interval=100) 40 plt.show()
2.6、画其他图形
1 import matplotlib.pyplot as plt 2 plt.rcdefaults() 3 4 import numpy as np 5 import matplotlib.pyplot as plt 6 import matplotlib.path as mpath 7 import matplotlib.lines as mlines 8 import matplotlib.patches as mpatches 9 from matplotlib.collections import PatchCollection 10 11 12 def label(xy, text): 13 y = xy[1] - 0.15 # shift y-value for label so that it's below the artist 14 plt.text(xy[0], y, text, ha="center", family='sans-serif', size=14) 15 16 17 fig, ax = plt.subplots() 18 # create 3x3 grid to plot the artists 19 grid = np.mgrid[0.2:0.8:3j, 0.2:0.8:3j].reshape(2, -1).T 20 21 patches = [] 22 23 # add a circle 24 circle = mpatches.Circle(grid[0], 0.1, ec="none") 25 patches.append(circle) 26 label(grid[0], "Circle") 27 28 # add a rectangle 29 rect = mpatches.Rectangle(grid[1] - [0.025, 0.05], 0.05, 0.1, ec="none") 30 patches.append(rect) 31 label(grid[1], "Rectangle") 32 33 # add a wedge 34 wedge = mpatches.Wedge(grid[2], 0.1, 30, 270, ec="none") 35 patches.append(wedge) 36 label(grid[2], "Wedge") 37 38 # add a Polygon 39 polygon = mpatches.RegularPolygon(grid[3], 5, 0.1) 40 patches.append(polygon) 41 label(grid[3], "Polygon") 42 43 # add an ellipse 44 ellipse = mpatches.Ellipse(grid[4], 0.2, 0.1) 45 patches.append(ellipse) 46 label(grid[4], "Ellipse") 47 48 # add an arrow 49 arrow = mpatches.Arrow(grid[5, 0] - 0.05, grid[5, 1] - 0.05, 0.1, 0.1, width=0.1) 50 patches.append(arrow) 51 label(grid[5], "Arrow") 52 53 # add a path patch 54 Path = mpath.Path 55 path_data = [ 56 (Path.MOVETO, [0.018, -0.11]), 57 (Path.CURVE4, [-0.031, -0.051]), 58 (Path.CURVE4, [-0.115, 0.073]), 59 (Path.CURVE4, [-0.03 , 0.073]), 60 (Path.LINETO, [-0.011, 0.039]), 61 (Path.CURVE4, [0.043, 0.121]), 62 (Path.CURVE4, [0.075, -0.005]), 63 (Path.CURVE4, [0.035, -0.027]), 64 (Path.CLOSEPOLY, [0.018, -0.11]) 65 ] 66 codes, verts = zip(*path_data) 67 path = mpath.Path(verts + grid[6], codes) 68 patch = mpatches.PathPatch(path) 69 patches.append(patch) 70 label(grid[6], "PathPatch") 71 72 # add a fancy box 73 fancybox = mpatches.FancyBboxPatch( 74 grid[7] - [0.025, 0.05], 0.05, 0.1, 75 boxstyle=mpatches.BoxStyle("Round", pad=0.02)) 76 patches.append(fancybox) 77 label(grid[7], "FancyBboxPatch") 78 79 # add a line 80 x, y = np.array([[-0.06, 0.0, 0.1], [0.05, -0.05, 0.05]]) 81 line = mlines.Line2D(x + grid[8, 0], y + grid[8, 1], lw=5., alpha=0.3) 82 label(grid[8], "Line2D") 83 84 colors = np.linspace(0, 1, len(patches)) 85 collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3) 86 collection.set_array(np.array(colors)) 87 ax.add_collection(collection) 88 ax.add_line(line) 89 90 plt.subplots_adjust(left=0, right=1, bottom=0, top=1) 91 plt.axis('equal') 92 plt.axis('off') 93 94 plt.show()
2.7、画点图
1 from numpy import *; 2 import numpy as np 3 import matplotlib.pyplot as plt 4 5 N = 50 6 x = np.random.rand(N) 7 y = np.random.rand(N) 8 colors = np.random.rand(N) 9 area = np.pi * (15 * np.random.rand(N))**2 10 plt.scatter(x, y, s=area, c=colors, alpha=0.5, marker=(9, 3, 30)) 11 plt.show()
三、总结
使用python中的库,我们可以按照自己的想法来画图,但是需要注意一些细节上的东西,比如尺寸和刻度,比如颜色,字体,以及相应对比的数据,特别是用于数据分析上面的对比,我们需要重点掌握。