• Python实用技术二:数据分析和可视化(2)


    目录

    一,多维数组库numpy

    1,操作函数:​

    2,numpy数组元素增删 

    1)添加数组元素

    2)numpy删除数组元素

    3)在numpy数组中查找元素

    4)numpy数组的数学运算

    3,numpy数组的切片

    二,数据分析库pandas

    1,DataFrame的构造和访问

    Series是一维表格,每个元素带标签且有下标,兼具列表和字典的访问形式

    DataFrame是带行列标签的二维表格,每一列都是一个Series

    2,DataFrame的切片和统计 

     3,DataFrame的分析统计

    4,DataFrame的修改增删

    5,读写excel和csv文档

     1)用pandas读excel文档

    2)用pandas读写csv文件

    三,用matplotlib进行数据展示

    1,绘制直方图

     2,绘制堆叠直方图

    3,绘制对比直方图(有多组数据)

    4,绘制散点,折线图

    5,绘制饼图

     6,绘制热力图

    7,绘制雷达图

    8,绘制多层雷达图

    9,多子图绘制

    一,多维数组库numpy

    ➢多维数组库,创建多维数组很方便,可以替代多维列表
    ➢速度比多维列表快
    ➢支持向量和矩阵的各种数学运算
    ➢所有元素类型必须相同

    1,操作函数:

    1. import numpy as np #以后numpy简写为np
    2. print (np.array([1,2,3]) ) #>>[1 2 3]
    3. print (np. arange(1,9,2) ) #>>[13 5 7]
    4. print (np. linspace(1,10,4)) #>>[ 1. 4. 7. 10. ]
    5. print (np . random. randint (10,20, [2,3]) )
    6. #>>[[12 19 12]
    7. #>> [19 13 10 ]]
    8. print (np . random. randint (10,20,5) ) #>> [12 19 19 10 13]
    9. a = np. zeros (3)
    10. print (a)
    11. #>>[ 0. 0. 0.]
    12. print(list(a) )
    13. #>>[0.0,0.0,0.0]
    14. a = np. zeros((2 ,3) ,dtype=int) #创建- t个23列的元素都是整数0的数组

    1. import numpy as np
    2. b = np.array([i for i in range (12) ])
    3. #b是[ 0 1 5 6 7 8 9 10 11]
    4. a = b.reshape( (3,4) )
    5. #转换成34列的数组,b不变
    6. print (len(a) )
    7. #>>3 a有3行
    8. print(a. size )
    9. #>>12 a的元素个数是12
    10. print (a. ndim)
    11. #>>2 a是2维的
    12. print (a. shape)
    13. #>>(3, 4) a是3行4列
    14. print (a. dtype)
    15. #>>int32 a的元素类型 是32位的整数
    16. L = a.tolist ()
    17. #转换成列表,a不变
    18. print (L)
    19. #>>[[0,1,2,3],[4,5,6,7],[8,9,10,11]]
    20. b = a. flatten ()
    21. #转换成一维数组
    22. print (b)
    23. #>>[0 1 2 3 5 6 7 8 9 10 11]

    2,numpy数组元素增删 

     numpy数组一旦生成,元素就不能增删。上面 函数返回一个新的数组。

    1)添加数组元素

    1. import numpy as np
    2. a = np.array((1,2,3) )
    3. #a是[123]
    4. b = np. append(a,10)<
    5. #a不会发生变化
    6. print (b)
    7. #>>[1 2 3 10]
    8. print (np. append(a, [10,20] ) )
    9. #>>[1 2 3 10 20]
    10. C=np. zeros ( (2,3) , dtype=int)
    11. #c是23列的全0数组
    12. print (np. append(a,c) )
    13. #>>[1 2 3 0 0 0 0 0 0]
    14. print (np. concatenate( (a, [10,20] ,a)) )
    15. #>>[1 2 3 10 20 1 2 3]
    16. print (np. concatenate( (C, np. array([[10 ,20,30]] ) ) ) )
    17. #c拼接一行[10, 20 ,30]得新数组
    18. print (np. concatenate( (C, np.array([[1,2], [10,20]])) ,axis=1) )
    19. #c的第0行拼接了12两个元素、第1行拼接了10 , 20两个新元素后得到新数组

    2)numpy删除数组元素

    1. import numpy as np
    2. a = np.array((1,2,3,4) )
    3. b = np.delete(a,1) #删除a中下标为1的元素, a不会改变
    4. print (b)
    5. #>>[1_ 3 4]
    6. b = np.array([[1,2,3,4] ,[5,6, 7,8], [9,10,11,121])
    7. print (np. delete (b,1 ,axis=0) )
    8. #删除b的第1行得新数组
    9. #>>[[1 2 3 4]
    10. #>>[9 10 11 12]]
    11. print (np. delete (b,1 ,axis=1) )
    12. #删除b的第1列得新数组
    13. print (np. delete (b,[1,2] ,axis=0) )
    14. #删除b的第1行和第2行得新数组
    15. print (np. delete (b,[1,3] ,axis=1) )
    16. #删除b的第1列和第3列得新数组

    3)在numpy数组中查找元素

    1. import numpy as np
    2. a = np.array( (1,2,3,5,3,4) )
    3. pos = np. argwhere(a==3)
    4. #pos是[[2] [4] ]
    5. a = np.array([[1,2,3] , [4,5,2]])
    6. print(2 in a)
    7. #>>True
    8. pos = np. argwhere(a==2)
    9. #pos是[[0 1] [1 2]]
    10. b = a[a>2]
    11. #抽取a中大于2的元素形成一个一维数组
    12. print (b)
    13. #>>[3 4 5]
    14. a[a>2]=-1
    15. #a变成[[12-1][-1-12]]

    4)numpy数组的数学运算

    1. import numpy as np
    2. a = np.array( (1,2,3,4) )
    3. b=a+1
    4. print (b)
    5. #>>[2 3 4 5]
    6. print (a*b)
    7. #>>[2 6 12 20] a,b对应元素相乘
    8. print (a+b)
    9. #>>[3579]a,b对应元素相加
    10. c = np.sqrt(a*10) #a*10是[10 20 30 40]
    11. print(c)
    12. #>>[ 3. 16227766 4. 47213595 5. 47722558 6.32455532]

    3,numpy数组的切片

    numpy数组的切片是“视图”,是原数组的一部分,而非一部分的拷贝
     

    1. import numpy as np
    2. a=np.arange(8)
    3. #a是[0 1 2 3 4 5 6 7]
    4. b = a[3:6]
    5. #注意,b是a的一部分
    6. print (b)
    7. #>>[3 4 5]
    8. c = np.copy(a[3:6])
    9. #c是a的一部分的拷贝
    10. b[0] = 100
    11. #会修改a
    12. print(a)
    13. #>>[ 0 1 2 100 4 6 7]
    14. print(c)
    15. #>>[3 4 5] c不受b影响
    16. a = np.array([[1,2,3,4] ,[5,6,7,8] , [9,10,11,12] , [13,14,15,16]])
    17. b = a[1:3,1:4]
    18. #b是>>[[678][101112]]

    二,数据分析库pandas

    1,DataFrame的构造和访问

    ➢核心功能是在二维表格上做各种操作,如增删、修改、求- -列数据的和、方差、中位数、平均数等
    ➢需要numpy支持
    ➢如果有openpyxI或xIrd或xIwt支持,还可以读写excel文档。
    ➢最关键的类: DataFrame,表示二维表格
     

    pandas的重要类:Series

    Series是一维表格,每个元素带标签且有下标,兼具列表和字典的访问形式
     

    1. import pandas as pd
    2. s = pd. Series (data=[80, 90,100] , index=['语文', '数学', '英语'])
    3. for x in s:
    4. #>>80 90 100
    5. print(x,end=" ")
    6. print ("")
    7. print(s['语文'] ,s[1])
    8. #>>80 90 标签和序号都可以作为下标来访问元
    9. print(s[0:2] [ '数学'])
    10. #>>90 s[0:2]是切片
    11. print(s['数学': '英语'] [1])
    12. #>>100
    13. for i in range (len (s. index) ) :
    14. #>>语文 数学 英语
    15. print(s. index[i] ,end = " ")
    16. s['体育'] = 110
    17. #在尾部添加元素,标签为'体育',值为110
    18. s. pop('数学')
    19. #删除标签为'数学’的元素
    20. s2 = s. append (pd . Series (120, index = [' 政治'])) #不改变s
    21. print(s2['语文'] ,s2['政治'])
    22. #>>80 120
    23. print (1ist(s2) )
    24. #>>[80,100, 110, 120]
    25. print(s.sum() ,s.min() ,s .mean() ,s . median() )
    26. #>>290 80 96. 66666666667 100.0输出和、 最小值、平均值、中位数>
    27. print (s . idxmax() ,s. argmax () )
    28. #>>体育 2 输出最大元素的标签和下标

    DataFrame是带行列标签的二维表格,每一列都是一个Series
     

    1. import pandas as pd
    2. pd.set_ option( 'display . unicode.east asian width' , True)
    3. #输出对齐方面的设置
    4. scores = [['男' ,108 ,115,97] ,['女' ,115,87,105] , ['女' ,100, 60 ,130]
    5. ['男' ,112,80,50]]
    6. names = ['刘一哥,'王二姐’,'张三妹',李四弟'] .
    7. courses = ['性别', '语文', '数学', '英语']
    8. df = . pd.DataFrame (data=scores ,index = names , columns = courses)
    9. print (df)

    1. print (df. values[0] [1] , type (df. values) ) #>>108.
    2. print (list (df. index) )
    3. #>>['刘一哥','王二姐','张三妹','李四弟']
    4. print (list (df. columns) )
    5. #>>['性别','语文','数学','英语']
    6. print (df . index[2] ,df . columns[2]) #>>张三妹 数学
    7. s1 = df['语文']
    8. #s1是个Series,代表'语文'那一列
    9. print(s1['刘一哥'] ,s1[0])
    10. #>>108 108 刘一哥语文成绩
    11. print(df['语文']['刘一哥'])
    12. #>>108 列索引先写
    13. s2 = df.1oc['王二姐']
    14. #s2也是个Series,代表“王二姐”那一行
    15. print(s2['性别'] ,s2['语文'] ,s2[2])
    16. #>>女 115 87 二姐的性别、语文和数学分数

    2,DataFrame的切片和统计 

    1. #DataFrame的切片:
    2. #1loc[行选择器,.列选择器] 用下标做切片
    3. #Ioc[行选择器,列选择器] 用标签做切片
    4. #DataFrame的切片是视图
    5. df2 = df. iloc[1:3] #行切片,是视图,选1 ,2两行
    6. dt2 = df.1c['王二姐':张三妹'] #和上一行等价
    7. print (df2)

    1. df2 = df. i1oc[: ,0:3] #列切片(是视图),选01. 2三列
    2. df2 = df.1oc[:, '性别': '数学'] #和上一行等价
    3. print (df2)

    1. df2 = df.i1oc[:2,[1,3]] #行列切片
    2. df2 = df.1oc[:'王二姐',['语文', '英语']] #和上一行等价
    3. print (df2)

    1. df2 = df.i1oc[[1,3] ,2:4] #取第13行,第23<
    2. df2 = df.1oc[['王二姐' , '李四弟'],'数学': '英语'] #和上一行等价
    3. print (df2)

     3,DataFrame的分析统计

    1. print ("---下面是DataFrame的分析和统计---")
    2. print (df. T)
    3. #df . T是df的转置矩阵,即行列互换的矩阵
    4. print (df . sort_ values ( '语文' , ascending=False)) #按语文成绩降序排列
    5. print (df.sum() [ '语文'] ,df .mean() ['数学'],df .median() ['英语'])
    6. #>>435 85.5 101.0语文分数之和、 数学平均分、英语中位数
    7. print(df .min() ['语文'] ,df .max() ['数学'])
    8. #>>100 115 语文最低分,数学最高分
    9. print (df .max(axis = 1)['王二姐'1) #>>115 二姐的最高分科目的分数
    10. print (df['语文' ] . idxmax() )
    11. #>>王二姐 语文最高分所在行的标签
    12. print(df['数学] . argmin())
    13. #>>2 数学最低分所在行的行号
    14. print (df.1oc[ (df['语文'] > 100) & (df['数学'] >= 85)])

    4,DataFrame的修改增删

    1. print ("---下面是DataFrame的增删和修改---")
    2. df.1oc['王二姐', '英语'] = df. iloc[0,1] = 150 #修改王二姐英语和刘一哥语文成绩
    3. df['物理'] = [80, 70,90,100]
    4. #为所有人添加物理成绩这-列
    5. df. insert(1, "体育", [89,77, 76,45])
    6. #为所有人插入体育成绩到第1
    7. df.1oc['李四弟'] = ['男' ,100 ,100 ,100 ,100,100] #修改李四弟全部信息
    8. df.1oc[: , '语文'] = [20,20,20,20]
    9. #修改所有人语文成绩
    10. df.1oc[ '钱五叔'] = [ '男' , 100 , 100 ,100, 100 , 100]
    11. #加一行
    12. df.1oc[: , '英语'] += 10
    13. #>>所有人英语加10分
    14. df. columns = ['性别', '体育', '语文', '数学', 'English', '物理'] #改列标签
    15. print (df)

     

    1. df.drop( ['体育', '物理'] ,axis=1, inplace=True) #删除体育和物理成绩
    2. df.drop( '王二姐' ,axis = 0,inplace=True)
    3. #删除王二姐那一行
    4. print (df)

    1. df.drop ( [df. index[i] for i in range(1,3) ] ,axis=0 , inplace = True)
    2. #删除第1,2
    3. df .drop( [df . columns[i] for i in range(3) ] ,axis = y 1 , inplace=
    4. True) #删除第02

    5,读写excel和csv文档

    ➢需要openpyxI(对 .xIsx文件)或xIrd或xIwt支持(老的.xls文件)
    ➢读取的每张工作表都是一个DataFrame

     1)用pandas读excel文档

    1. import pandas as pd
    2. pd.set option ( ' display . unicode.east asian width' , True)
    3. dt = pd. read excel ("'excel sample.xlsx" , sheet name= [ '销售情况' ,1] ,
    4. index col=0) #读取第0和第1张二工作表
    5. df =
    6. dt [ '销售情况']
    7. #dt是字典,df是DataFrame
    8. print (df. iloc[0,0] ,df.loc[ 'I睡袋' , '数量'])
    9. #>>4080 4080
    10. print (df)

    1. print (pd. isnu1l (df.1oc['彩盒', '销售额']))
    2. #>> True
    3. df . fillna (0 , inplace= =True)
    4. #将所有NaNa用0替换
    5. print(df.loc[ '彩盒' , '销售额'] ,df. iloc[2,2] )
    6. #>>0.0 0.0

    df.to excel (filename , sheet_ name="Sheet1" ,na_ rep='',.. ......)
    ➢将DataFrame对象df中的数据写入exce1文档filename中的"Sheet1"工作表, NaN用' '代替。
    ➢会覆盖原有的filename文件
    ➢如果要在一个excel文档中写入多个工作表,需要用ExcelWrite
     

    1. # (接.上面程序)
    2. writer = pd. Exce 1Writer ("new.x1sx")
    3. #创建ExcelWri ter对象
    4. df. to exce1 (writer , sheet_ name="S1")
    5. df.T. to exce1 (writer, sheet_ name="S2")
    6. #转置矩阵写入
    7. df.sort_ values( '销售额' , ascending= False) . to exce1 (writer ,
    8. sheet_ name="S3")
    9. #按销售额排序的新DataFrame写入工作表s3
    10. df[ '销售额'] . to excel (writer ,sheet_ name="S4")
    11. #只写入一列
    12. writer . save ()

    2)用pandas读写csv文件

    1. df. to_ csv (" result. csv" ,sep=" ," ,na rep= 'NA' ,
    2. float_ format="号 .2f" , encoding="gbk")
    3. df = pd. read csv (" result. csv")

    三,用matplotlib进行数据展示

    1,绘制直方图

    1. import matp1otlib. pYp1ot as plt #以后plt等价于ma tplotlib . pyplot
    2. from ma tp1ot1ib import rcParams
    3. rcParams[ ' font. family'] = rcParams[ ' font. sans-serif'] = ' SimHei '
    4. #设置中文支持,中文字体为简体黑体
    5. ax = p1t. figure() .add subp1ot ()
    6. #建图,获取子图对象ax
    7. ax.bar(x = (0.2,0.6,0.8,1.2) ,height = (1,2,3,0.5) ,width = 0.1)
    8. #x表示4个柱子中心横坐标分别是0.2,0.6,0.8,1
    9. #height表示4个柱子高度分别是1,2,3,0.5
    10. #width表示柱子宽度0.1
    11. ax.set_ title ('我的直方图)
    12. #设置标题
    13. p1t. show ()
    14. #显示绘图结果
    1. 纵向
    2. ax.bar(x = (0.2,0.6,0.8,1.2) ,height = (1,2,3,0.5) ,width = 0.1)
    3. 横向
    4. ax.barh(y = (0.2,0.6,0.8,1.2) ,width = (1,2,3,0.5) ,height = 0.1)

     2,绘制堆叠直方图

    1. import ma tplotlib. pyp1ot as p1t
    2. ax = plt. figure() . add subp1ot()
    3. labels = ['Jan' ,'Feb' ,'Mar' ,lApr']
    4. num1 = [20301535]
    5. #Dept1的数据
    6. num2 = [15304020]
    7. #Dept2的数据
    8. cordx = range (len (num1) )
    9. #x轴刻度位置
    10. rects1 = ax.bar(x = cordx,height=num1, width=0.5, color=' red' ,
    11. label="Dept1")
    12. rects2 = ax.bar(x = cordx, height=num2, width=0 .5,color='green' ,
    13. label="Dept2",bottom= =num1 )
    14. ax.set_ y1im(0100)
    15. #y轴坐标范围
    16. ax. set_ ylabel ("Profit")
    17. #y轴含义(标签)
    18. ax. set xticks (cordx )
    19. #设置x轴刻度位置
    20. ax. set_ xlabel ("In year 2020")
    21. #x轴含义(标签)
    22. ax.set_ title ("My Company")
    23. ax. legend()
    24. #在右上角显示图例说明
    25. p1t. show ()

    3,绘制对比直方图(有多组数据)

    1. import matplotlib. pyp1ot as plt
    2. ax =. plt. figure (figsize= (10,5)) . add_ subplot () #建图,获取子图对象ax
    3. ax.set ylim(0, 400)
    4. #指定y轴坐标范围
    5. ax.set xlim(0, 80)
    6. #指定x轴坐标范围
    7. #以下是3组直方图的数据
    8. x1=[71727374757]
    9. #第一-组直方图每个柱子中心点的横坐标
    10. x2 = [132333435363] #第二组直方图每个柱子中心点的横坐标
    11. x3 = [102030405060]
    12. y1 = [413913693914]
    13. #第一组直方图每个柱子的高度
    14. y2 = [12315, 201057937] #第二组直方图每个柱子的高度
    15. y3 = [12491204264221, 175]
    16. rects1 = ax.bar(x1, y1,facecolor='red' ,width=3, label =_ ' Iphone' )
    17. rects2 = ax.bar (x2,y2,facecolor='green' ,width=3, label = ' Huawei ' )
    18. rects3 = ax.bar(x3, y3,facecolor= ='blue',width=3,label = ' Xiaomi )
    19. ax.set_ xticks (x3)
    20. #x轴在x3中的各坐标点下面加刻度
    21. ax. set_ xticklabels( ('A1', 'A2', 'A3', 'A4' , 'A5', 'A6') )
    22. #指定x轴上每- -刻度下方的文字
    23. ax. legend ()
    24. #显示右.上角三组图的说明
    25. def 1abe1 (ax , rects) : #在rects的每个柱子顶端标注数值
    26. for rect in rects :
    27. height = rect.get_ height()
    28. ax. text (rect.get_ x() + rect.get_ width() /2,
    29. height+14, str (height) , rotation=90) #文字旋转90度
    30. 1abe1 (ax, rects1)
    31. label (ax , rects2)
    32. labe1 (ax, rects3)
    33. p1t. show ()

    4,绘制散点,折线图

    1. import math , random
    2. import matplotlib.pyplot as plt
    3. def drawPlot(ax) :
    4. xs = [i / 100 for i in range (1500)] #1500个 点的横坐标,间隔0 .01
    5. ys = [10*math.sin(x) for X in xs]
    6. #对应曲线y=10*sin (x).上的1 500个点的y坐标
    7. ax.plot (xs,ys, "red" ,label = "Beijing") #画曲线y= =10*sin (x)
    8. ys = list (range(-18,18) )
    9. random. shuffle (ys)
    10. ax. scatter (range(16),ys[:16] ,c = "blue") #画散点
    11. ax.plot (range(16),ys[:16] ,"blue", label=" Shanghai") #画折线
    12. ax . legend ()
    13. #显示右.上角的各条折线说明
    14. ax.set xticks (range (16) )
    15. #x轴在坐标0,1.. .15处加刻度
    16. ax. set_ xticklabels (range (16)) #指定x轴每个刻度 下方显示的文字
    17. ax = plt. figure (figsize=(104) ,dpi=100) .add_ subp1ot() #图像长宽和清晰度
    18. drawP1ot (ax)
    19. p1t. show ()

    5,绘制饼图

    1. import matplotlib.pyplot as p1t .
    2. def drawPie (ax) :
    3. 1bs = ( 'A','B', 'C',
    4. 'D' )
    5. #四个扇区的标签
    6. sectors = [1629.5544.4510]
    7. #四个扇区的份额(百分比)
    8. exp1 = [00.1, 00]
    9. #四个扇区的突出程度
    10. ax.pie (x=sectors,labels=lbs, exp1ode=exp1,
    11. autopct=18.2f' , shadow=True, labeldistance=1 .1,
    12. pctdistance = 0 .6, startangle = 90)
    13. ax.set_ title ("pie sample")
    14. #饼图标题
    15. ax = p1t. figure() .add subp1ot()
    16. drawPie (ax)
    17. p1t. show()

     6,绘制热力图

    1. import numpy as np
    2. from matplotlib import pyp1ot as plt
    3. data = np. random. randint(010030) .reshape (56)
    4. #生成一一个5行六列,元素[0, 100]内的随机矩阵
    5. xlabels = [ 'Beijing', ' Shanghai''Chengdu' ,
    6. ' Guangzhou'' Hangzhou'
    7. ' Wuhan' ]
    8. ylabels=['2016''2017''2018''2019''20201]
    9. ax = plt. figure (figsize=(10,8)) .add_ subp1ot()
    10. ax.set yticks (range (len (ylabels))) #y轴在坐标 [0 , len (ylabels))处加刻度
    11. ax.set_ yticklabels (ylabels) #设置y轴刻度文字
    12. ax. set_ xticks (range (len (xlabels) ) )
    13. ax.set xticklabels (xlabels)
    14. heatMp = ax. imshow (data,cmap=plt. cm.hot, aspect=' auto' ,
    15. vmin =0,vmax=100)
    16. for i in range (1en (x1abe1s) ) :
    17. for j in range (1en (y1abe1s) ) :
    18. ax. text(i,j ,data[j] [i] ,ha = "center" ,va = "center"
    19. color =
    20. "blue" ,size=26)
    21. p1t. colorbar (heatMp)
    22. #绘制右边的颜色-数值对照柱
    23. plt . xticks (rotation=45 , ha=" right") #将x轴刻度文字进行旋转, 且水平方向右对齐
    24. p1t. title ("Sales Volume (ton) ")
    25. p1t. show ()

    7,绘制雷达图

    1. import matplotlib. pyplot as plt
    2. from matplotlib import rcParams
    3. #处理汉字用
    4. def drawRadar (ax) :
    5. pi = 3.1415926
    6. labels = ['EQ', 'IQ','人缘' , '魅力', '财富' , '体力'] #6个属性的名称
    7. attrNum = len (labels)
    8. #attrNum是属性种类数,处等于6
    9. data = [7 ,6,8,9,8,2]
    10. #六个属性的值
    11. angles = [2*pi *i/ attrNum for i in range (attrNum) ]
    12. #angles是以弧度为单位的6个属性对应的6条半径线的角度
    13. angles2 = [x * 180/pi for x in angles]
    14. #angles2是以角度为单位的6个属性对应的半径线的角度
    15. ax.set ylim(010)
    16. #限定半径线上的坐标范围
    17. ax. set_ thetagrids (angles2,labels , fontproperties="SimHei" )
    18. #绘制6个属性对应的6条半径
    19. ax. fi1l (angles,data, facecolor= ; : 6 'g' ,alpha= =0.25)
    20. #填充,alpha :透明度
    21. rcParams[' font. family'] = rcParams[' font. sans-serif'] = ' SimHei '
    22. #处理汉字
    23. ax = p1t. figure() . add_ subplot (projection = "polar")
    24. #生成极坐标形式子图
    25. drawRadar (ax)
    26. p1t. show ()

    8,绘制多层雷达图

    1. import matplotlib.pyplot as p1t
    2. from ma tplot1ib import rcPar ams
    3. rcParams[ ' font. family'] = rcParams[ ' font. sans-serif'] = ' SimHei !
    4. pi = 3.1415926
    5. labels = ['EQ', 'IQ','人缘', '魅力',财富', '体力] #6个属性的名称
    6. attrNum = len (labels)
    7. names = (张三',李四'王五
    8. data = [[0.40,0.32,0.35] ,
    9. [0.85,0.35,0.30] ,
    10. [0.40,0.32,0.35],[0.40,0.82,0.75] ,
    11. [0.14,0.12,0.35] ,
    12. [0.80,0.92,0.35]]
    13. #三个人的数据
    14. angles = [2*pi*i/attrNum for i in range (attrNum) ]
    15. angles2 = [x * 180/pi for x in ang1es]
    16. ax = p1t. figure() .add_ subp1ot (projection = "polar")
    17. ax. set_ the tagrids (angles2 , labels)
    18. ax.set_ title('三巨头人格分析',y = 1.05) #y指明标题垂直位置
    19. ax. legend (names , 1oc=(0.95,0.9)) #画出右上角不同人的颜色说明
    20. plt. show ()

    9,多子图绘制

    1. #程序中的import、汉字处理及drawRadar、 drawPie、 drawPlot函数略, 见前面程序
    2. fig = plt. figure (figsize=(8,8) )
    3. ax = fig.add subplot(2,2,1) #窗口分割成2*2,取位于第1个方格的子图
    4. drawPie (ax)
    5. ax = fig.add subplot(2 ,2 ,2 ,projection = "polar" )
    6. drawRadar (ax)
    7. ax = p1t. subp1ot2grid( (2, 2),(10),colspan=2)
    8. #或写成: ax = fig.add subplot(2,1,2)
    9. drawPlot (ax)
    10. plt. figtext(0.05,0.05, ' subplot sample' )
    11. #显示左下角的图像标题
    12. plt. show ()
  • 相关阅读:
    【Linux】--- 详解Linux软件包管理器yum和编辑器vim
    经典BN很NB,精读论文《Batch Normalization》
    协议类型(总结为主,非详细)
    机试(cs,se)
    leetcode 1 两数之和
    02_SpingBoot 入门案例
    Linux系统下KVM虚拟机的基本管理和操作
    基于单片机设计的防煤气泄漏装置
    Linux忘记密码
    debug技巧之使用arthas调试
  • 原文地址:https://blog.csdn.net/m0_63309778/article/details/133471293