沉淀再出发:用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.pyplot as plt
3 np.random.seed(19680801)
4 mu1, sigma1 = 100, 15
5 mu2, sigma2 = 80, 15
6 x1 = mu1 + sigma1 * np.random.randn(10000)
7 x2 = mu2 + sigma2 * np.random.randn(10000)
8 # the histogram of the data
9 # 50:将数据分成50组
10 # facecolor:颜色;alpha:透明度
11 # density:是密度而不是具体数值
12 n1, bins1, patches1 = plt.hist(x1, 50, density=True, facecolor='g', alpha=1)
13 n2, bins2, patches2 = plt.hist(x2, 50, density=True, facecolor='r', alpha=0.2)
14 # n:概率值;bins:具体数值;patches:直方图对象。
15 plt.xlabel('Smarts')
16 plt.ylabel('Probability')
17 plt.title('Histogram of IQ')
18 plt.text(110, .025, r'$\mu=100,\ \sigma=15$')
19 plt.text(50, .025, r'$\mu=80,\ \sigma=15$')
20 # 设置x,y轴的具体范围
21 plt.axis([40, 160, 0, 0.03])
22 plt.grid(True)
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()
1 import matplotlib.pyplot as plt
2 labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
3 sizes = [15, 30, 45, 10]
4 # 设置分离的距离,0表示不分离
5 explode = (0, 0.1, 0, 0)
6 plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
7 shadow=True, startangle=90)
8 # Equal aspect ratio 保证画出的图是正圆形
9 plt.axis('equal')
10 plt.show()
1 import numpy as np
2 import matplotlib.pyplot as plt
3 # 设置每环的宽度
4 size = 0.3
5 vals = np.array([[60., 32.], [37., 40.], [29., 10.]])
6 # 通过get_cmap随机获取颜色
7 cmap = plt.get_cmap("tab20c")
8 outer_colors = cmap(np.arange(3)*4)
9 inner_colors = cmap(np.array([1, 2, 5, 6, 9, 10]))
10 print(vals.sum(axis=1))
11 # [92. 77. 39.]
12 plt.pie(vals.sum(axis=1), radius=1, colors=outer_colors,
13 wedgeprops=dict(width=size, edgecolor='w'))
14 print(vals.flatten())
15 # [60. 32. 37. 40. 29. 10.]
16 plt.pie(vals.flatten(), radius=1-size, colors=inner_colors,
17 wedgeprops=dict(width=size, edgecolor='w'))
18 # equal 使得为正圆
19 plt.axis('equal')
20 plt.show()
1 import numpy as np
2 import matplotlib.pyplot as plt
3 np.random.seed(19680801)
4 N = 10
5 theta = np.linspace(0.0, 2 * np.pi, N, endpoint=False)
6 radii = 10 * np.random.rand(N)
7 width = np.pi / 4 * np.random.rand(N)
8 ax = plt.subplot(111, projection='polar')
9 bars = ax.bar(theta, radii, width=width, bottom=0.0)
10 # left表示从哪开始,
11 # radii表示从中心点向边缘绘制的长度(半径)
12 # width表示末端的弧长
13 # 自定义颜色和不透明度
14 for r, bar in zip(radii, bars):
15 bar.set_facecolor(plt.cm.viridis(r / 10.))
16 bar.set_alpha(0.5)
17 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()
2.8、画数学曲线
1 #coding:utf-8
2 import numpy as np
3 import matplotlib.pyplot as plt
4 x=np.linspace(0,10,1000)
5 y=np.sin(x)
6 z=np.cos(x**2)
7 #控制图形的长和宽单位为英寸,
8 # 调用figure创建一个绘图对象,并且使它成为当前的绘图对象。
9 plt.figure(figsize=(8,4))
10 #$可以让字体变得跟好看
11 #给所绘制的曲线一个名字,此名字在图示(legend)中显示。
12 # 只要在字符串前后添加"$"符号,matplotlib就会使用其内嵌的latex引擎绘制的数学公式。
13 #color : 指定曲线的颜色
14 #linewidth : 指定曲线的宽度
15 plt.plot(x,y,label="$sin(x)$",color="red",linewidth=2)
16 #b-- 曲线的颜色和线型
17 plt.plot(x,z,"b--",label="$cos(x^2)$")
18 #设置X轴的文字
19 plt.xlabel("Time(s)")
20 #设置Y轴的文字
21 plt.ylabel("Volt")
22 #设置图表的标题
23 plt.title("PyPlot First Example")
24 #设置Y轴的范围
25 plt.ylim(-1.2,1.2)
26 #显示图示
27 plt.legend()
28 #显示出我们创建的所有绘图对象。
29 plt.show()
1 #coding:utf-8
2 import numpy as np
3 import matplotlib.pyplot as plt
4 x=np.arange(0,5,0.1)
5 ## plot返回一个列表,通过line,获取其第一个元素
6 line,=plt.plot(x,x*x)
7 # 调用Line2D对象的set_*方法设置属性值 是否抗锯齿
8 line.set_antialiased(False)
9 # 同时绘制sin和cos两条曲线,lines是一个有两个Line2D对象的列表
10 lines = plt.plot(x, np.sin(x), x, np.cos(x))
11 ## 调用setp函数同时配置多个Line2D对象的多个属性值
12 plt.setp(lines, color="r", linewidth=2.0)
13 plt.show()
1 import numpy as np
2 import matplotlib.pyplot as plt
3 x = np.arange(0., 5., 0.2)
4 # 红色破折号, 蓝色方块 ,绿色三角块
5 plt.plot(x, x, 'r--', x, x**2, 'bs', x, x**3, 'g^')
6 plt.show()
2.9.画多个子图
1 import matplotlib.pyplot as plt
2 '''
3 subplot(numRows, numCols, plotNum)
4 numRows行 * numCols列个子区域
5 如果numRows,numCols和plotNum这三个数都小于10的话,可以把它们缩写为一个整数,
6 例如subplot(323)和subplot(3,2,3)是相同的
7 '''
8 for idx, color in enumerate("rgbyckbyc"):
9 plt.subplot(330+idx+1, facecolor=color)
10 plt.show()
11 plt.subplot(221) # 第一行的左图
12 plt.subplot(222) # 第一行的右图
13 #第二行全占
14 plt.subplot(212) # 第二整行
15 plt.show()
16
17 plt.subplot(331, facecolor='r')
18 plt.show()
2.10、标记刻度
1 import matplotlib.pyplot as pl
2 from matplotlib.ticker import MultipleLocator, FuncFormatter
3 import numpy as np
4 x = np.arange(0, 4*np.pi, 0.01)
5 y = np.sin(x)
6 pl.figure(figsize=(8,4))
7 pl.plot(x, y)
8 ax = pl.gca()
9
10 def pi_formatter(x, pos):
11 """
12 比较罗嗦地将数值转换为以pi/4为单位的刻度文本
13 """
14 m = np.round(x / (np.pi/4))
15 n = 4
16 if m%2==0: m, n = m/2, n/2
17 if m%2==0: m, n = m/2, n/2
18 if m == 0:
19 return "0"
20 if m == 1 and n == 1:
21 return "$\pi$"
22 if n == 1:
23 return r"$%d \pi$" % m
24 if m == 1:
25 return r"$\frac{\pi}{%d}$" % n
26 return r"$\frac{%d \pi}{%d}$" % (m,n)
27 # 设置两个坐标轴的范围
28 pl.ylim(-1.5,1.5)
29 pl.xlim(0, np.max(x))
30 # 设置图的底边距
31 pl.subplots_adjust(bottom = 0.15)
32 pl.grid() #开启网格
33 # 主刻度为pi/4
34 ax.xaxis.set_major_locator( MultipleLocator(np.pi/4) )
35 # 主刻度文本用pi_formatter函数计算
36 ax.xaxis.set_major_formatter( FuncFormatter( pi_formatter ) )
37 # 副刻度为pi/20
38 ax.xaxis.set_minor_locator( MultipleLocator(np.pi/20) )
39 # 设置刻度文本的大小
40 for tick in ax.xaxis.get_major_ticks():
41 tick.label1.set_fontsize(16)
42 pl.show()
2.11、三维图
1 import matplotlib.pyplot as plt
2 from mpl_toolkits.mplot3d import Axes3D
3 import numpy as np
4
5 def fun(x,y):
6 #return np.power(x,2)+np.power(y,2)
7 return 2*(x*0.8+y*0.1)*(x*0.2+y*0.9)*(x*0.3+y*0.7)*(x*0.3+y*0.7)*(x*0.4+y*0.7)*(x*0.4+y*0.7)
8
9 def fun2(xx,yy):
10 return xx
11
12 fig1=plt.figure()
13 ax=Axes3D(fig1)
14 X=np.arange(0,1,0.01)
15 Y=np.arange(0,1,0.01)
16
17 XX=np.arange(0,1,0.01)
18 YY=np.arange(1,0,-0.01)
19
20 ZZ=np.arange(0,1,0.01)
21
22 ZZ,ZZ=np.meshgrid(ZZ,ZZ)
23
24 #ZZ=fun2(XX,YY)
25 X,Y=np.meshgrid(X,Y)
26 Z=fun(X,Y)
27 plt.title("This is main title")
28 ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.coolwarm)
29
30 ax.plot_surface(XX, YY, ZZ, rstride=1, cstride=1, cmap=plt.cm.coolwarm)
31
32 ax.set_xlabel(u'θ1', color='r')
33 ax.set_ylabel(u'θ2', color='g')
34 ax.set_zlabel('z label', color='b')
35 plt.show()
1 import numpy as np
2 import matplotlib.pyplot as plt
3 from mpl_toolkits.mplot3d import Axes3D
4 data = np.random.randint(0, 255, size=[40, 40, 40])
5 x, y, z = data[0], data[1], data[2]
6 ax = plt.subplot(111, projection='3d') # 创建一个三维的绘图工程
7 # 将数据点分成三部分画,在颜色上有区分度
8 ax.scatter(x[:10], y[:10], z[:10], c='y') # 绘制数据点
9 ax.scatter(x[10:20], y[10:20], z[10:20], c='r')
10 ax.scatter(x[30:40], y[30:40], z[30:40], c='g')
11 ax.set_zlabel('Z') # 坐标轴
12 ax.set_ylabel('Y')
13 ax.set_xlabel('X')
14 plt.show()
1 from matplotlib import pyplot as plt
2 import numpy as np
3 from mpl_toolkits.mplot3d import Axes3D
4 fig = plt.figure()
5 ax = Axes3D(fig)
6 X = np.arange(-4, 4, 0.25)
7 Y = np.arange(-4, 4, 0.25)
8 X, Y = np.meshgrid(X, Y)
9 R = np.sqrt(X**2 + Y**2)
10 Z = np.sin(R)
11 # 具体函数方法可用 help(function) 查看,如:help(ax.plot_surface)
12 ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap='rainbow')
13 plt.show()
2.12、画3d柱状图
1 #-*- coding:utf-8 -*-
2 import numpy as np
3 import matplotlib as mpl
4 import matplotlib.pyplot as plt
5 import random
6 import matplotlib.dates as mdates
7
8 from mpl_toolkits.mplot3d import Axes3D
9 #generate random numbers
10 Query_times1=range(0,50)
11 Query_times2=range(0,30)
12 list_random1=random.sample(Query_times1,25)
13 list_random2=random.sample(Query_times2,25)
14 mpl.rcParams['font.size'] = 8
15
16 fig = plt.figure()
17 ax = fig.add_subplot(111, projection='3d')
18
19 xs = np.arange(1,26)
20 ys =list_random1
21 ys2=list_random2
22 ys3=list_random1
23 ys4=list_random2
24 ys5=list_random1
25 ys6=list_random2
26 ys7=list_random1
27 ys8=list_random2
28
29
30 z1=3
31 total_width, n = 0.8, 2
32 width = total_width / n
33 color =plt.cm.Set2((np.arange(plt.cm.Set2.N)))
34 p1=ax.bar(xs, ys, z1, zdir='y', color='#FF0080', alpha=0.8,width=width,label='h=3,DA')
35 p2=ax.bar(xs + width, ys2, z1, zdir='y', color='CYAN', alpha=0.8,width=width,label='h=3,DGA')
36
37 z2=4
38 total_width, n = 0.8, 2
39 width = total_width / n
40 color =plt.cm.Set2((np.arange(plt.cm.Set2.N)))
41 p3=ax.bar(xs, ys3, z2, zdir='y', color='b', alpha=0.8,width=width,label='h=4,DA')
42 p4=ax.bar(xs + width, ys4, z2, zdir='y', color='#9AFF02', alpha=0.8,width=width,label='h=4,DGA')
43
44 z3=5
45 total_width, n = 0.8, 2
46 width = total_width / n
47 color =plt.cm.Set2((np.arange(plt.cm.Set2.N)))
48 p5=ax.bar(xs, ys5, z3, zdir='y', color='#FF8000', alpha=0.8,width=width,label='h=5,DA')
49 p6=ax.bar(xs + width, ys6, z3, zdir='y', color='violet', alpha=0.8,width=width,label='h=5,DGA')
50
51 z4=6
52 total_width, n = 0.8, 2
53 width = total_width / n
54 color =plt.cm.Set2((np.arange(plt.cm.Set2.N)))
55 p7=ax.bar(xs, ys7, z4, zdir='y', color='r', alpha=0.8,width=width,label='h=6,DA')
56 p8=ax.bar(xs + width, ys8, z4, zdir='y', color='#0072E3', alpha=0.8,width=width,label='h=6,DGA')
57
58 # ax.xaxis.set_major_locator(mpl.ticker.FixedLocator(xs))
59 # ax.yaxis.set_major_locator(mpl.ticker.FixedLocator(ys))
60
61 ax.set_xlabel('k-')
62 ax.set_ylabel('Spatial hierarchy (h)')
63 ax.set_zlabel('Count')
64 # plt.legend(loc='upper left')
65 #plt.legend(loc='upper left', bbox_to_anchor=(0.0,0.6),ncol=1,fancybox=True,shadow=False)#Control the position of the legend
66 plt.show()
2.13、柱状图、并列柱状图
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()
1 import numpy as np
2 import matplotlib.pyplot as plt
3 x = [1,2] #横坐标
4 y = [3,4] #第一个纵坐标
5 y1 = [5,6] #第二个纵坐标
6 x = np.arange(len(x)) #首先用第一个的长度作为横坐标
7 width = 0.05 #设置柱与柱之间的宽度
8 fig,ax = plt.subplots()
9 ax.bar(x,y,width,alpha = 0.9)
10 ax.bar(x+width,y1,width,alpha = 0.9,color= 'red')
11 ax.set_xticks(x +width/2)#将坐标设置在指定位置
12 ax.set_xticklabels(x)#将横坐标替换成
13 plt.show()
1 # -*- coding: utf-8 -*-
2 import matplotlib.pyplot as plt
3
4 name_list = ['Monday','Tuesday','Friday','Sunday']
5 num_list = [1.5,0.6,7.8,6]
6 num_list1 = [1,2,3,1]
7 x =list(range(len(num_list)))
8 total_width, n = 0.8, 2
9 width = total_width / n
10
11 plt.bar(x, num_list, width=width, label='boy',fc = 'y')
12 for i in range(len(x)):
13 x[i] = x[i] + width
14 plt.bar(x, num_list1, width=width, label='girl',tick_label = name_list,fc = 'r')
15 plt.legend()
16 plt.show()
1 import numpy as np
2 import matplotlib.pyplot as plt
3 size = 5
4 a = np.random.random(size)
5 b = np.random.random(size)
6 c = np.random.random(size)
7 x = np.arange(size)
8 # 有多少个类型,只需更改n即可
9 total_width, n = 0.8, 3
10 width = total_width / n
11 # 重新拟定x的坐标
12 x = x - (total_width - width) / 2
13 # 这里使用的是偏移
14 plt.bar(x, a, width=width, label='a')
15 plt.bar(x + width, b, width=width, label='b')
16 plt.bar(x + 2 * width, c, width=width, label='c')
17 plt.legend()
18 plt.show()
2.13、堆叠柱状图
1 # -*- coding: utf-8 -*-
2 import matplotlib.pyplot as plt
3
4 name_list = ['Monday','Tuesday','Friday','Sunday']
5 num_list = [1.5,0.6,7.8,6]
6 num_list1 = [1,2,3,1]
7 plt.bar(range(len(num_list)), num_list, label='boy',fc = 'y')
8 plt.bar(range(len(num_list)), num_list1, bottom=num_list, label='girl',tick_label = name_list,fc = 'r')
9 plt.legend()
10 plt.show()
1 import numpy as np
2 import matplotlib.pyplot as plt
3 size = 5
4 a = np.random.random(size)
5 b = np.random.random(size)
6 c = np.random.random(size)
7 x = np.arange(size)
8 # 这里使用的是偏移
9 plt.bar(x, a, width=0.5, label='a',fc='r')
10 plt.bar(x, b, bottom=a, width=0.5, label='b', fc='g')
11 plt.bar(x, c, bottom=a+b, width=0.5, label='c', fc='b')
12 plt.ylim(0, 2.5)
13 plt.legend()
14 plt.grid(True)
15 plt.show()
2.14、横排柱状图
1 # -*- coding: utf-8 -*-
2 import matplotlib.pyplot as plt
3
4 name_list = ['Monday','Tuesday','Friday','Sunday']
5 num_list = [1.5,0.6,7.8,6]
6 plt.barh(range(len(num_list)), num_list,tick_label = name_list)
7 plt.show()
三、总结
使用python中的库,我们可以按照自己的想法来画图,但是需要注意一些细节上的东西,比如尺寸和刻度,比如颜色,字体,以及相应对比的数据,特别是用于数据分析上面的对比,我们需要重点掌握。