• MatplotLib 第一部分


      1 import numpy as np
      2 import pandas as pd
      3 import matplotlib.pyplot as plt
      4 
      5 # matplotlib 是一个Python 的 2D图形包 。pyplot 封装了很多画图的函数
      6 
      7 # plt.show()函数  
      8 
      9 # plt.plot()函数 
     10 # 可以绘制线型图
     11 if 0:
     12     if 0:
     13         # 小试牛刀
     14         plt.plot([1, 2, 3, 4, 4, 3, 2, 1])  # 此时默认以索引作为x坐标
     15         plt.xlabel('x')
     16         plt.ylabel('y')
     17         pass
     18     if 0:
     19         # 基本用法
     20         # 1,指定x 和 y  :
     21         # plt.plot(x,y)
     22         # 2,默认参数  x为默认索引
     23         # plt.plot(y)
     24         plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
     25         pass
     26 # 字符参数
     27 if 0:
     28     # 表示颜色的字符参数
     29     if 1:
     30         '''
     31         'b' blue 
     32         'g' green
     33         r  red 
     34         c  cyan 青色
     35         m  magenta 品红 
     36         y  yellow 
     37         k  black  
     38         w  white  
     39         '''
     40 
     41         pass
     42 
     43     # 表示线型的字符参数
     44     if 1:
     45         '''
     46         -   实线  
     47         --  虚线 
     48         。。。。。。
     49         '''
     50         pass
     51 
     52     if 1:
     53         # 要求画出红色 圆点
     54         plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro')
     55         # r 是红色 o  是圆点
     56         pass
     57 
     58     pass
     59 
     60 # 显示范围
     61 if 0:
     62     # 与 Matlab类似 ,这里可以使用axis()指定坐标轴显示的范围
     63     # plt.axis([xmin,xmax,ymin,ymax ])
     64     plt.plot(range(10), [x ** 2 for x in range(10)])
     65     plt.axis([0, 10, 0, 100])
     66     pass
     67 
     68 # 传入Numpy 数组   (常用 )
     69 if 0:
     70     # 之前都是传入的是列表,其实plot 内部还是会将列表转为数组的
     71     # 所以,以后最常用的还是传入数组
     72 
     73     # 在一个图中绘制多条线
     74     arr = np.arange(0, 5, 0.2)  # 不包含 5   step 为 0.2
     75     plt.plot(arr, arr, 'r-',
     76              arr, arr ** 2, 'b--',
     77              arr, arr ** 3, 'k^',
     78              arr, arr ** 2 - arr + 10, 'gs'  # s 指的是 square
     79              )
     80 
     81     pass
     82 
     83 # 线条属性
     84 if 0:
     85     # 这里是通过关键词的方法而不是通过字符的方式来控制颜色,线型等...
     86     # 例如 通过linewidth 改变线宽  通过color 改变颜色
     87     x = np.linspace(-np.pi, np.pi)  # 等差数列  #固定个数用arange()
     88     y = np.sin(x)
     89     plt.plot(x, y, linewidth=4.0, color='r')
     90 
     91     pass
     92 
     93 # 使用 plt.plot()的返回值 来设置线条属性 
     94 if 0:
     95     #plot函数返回一个Line2D对象,每个对象代表输入的一对组合
     96     #eg:
     97     # line1,line2 = plt.plot(x1,y1,x2,y2)
     98     # line1 ,line2 为两个line2D 对象
     99 
    100     # lines = plt.plot(x1,y1,x2,y2,x3,y3)
    101     #lines 为3个Line2D对象组成的列表
    102 
    103     #我们可以使用这些返回值来对线条属性进行设置
    104 
    105     x = np.arange(-np.pi,np.pi,0.02)
    106     y = np.sin(x)
    107     line1 ,line2 = plt.plot(x,y,'r-',
    108                             x,y+1,'b--')
    109 
    110     line1.set_antialiased(False)  #关闭抗锯齿
    111 
    112 
    113 
    114 
    115 
    116 
    117 
    118 
    119     pass
    120 
    121 #可以使用plt.setp() 更简便地 修改线条的性质 
    122 if 0:
    123     x = np.arange(-np.pi,np.pi,0.02)
    124     y = np.sin(x)
    125     line = plt.plot(x,y)
    126     plt.setp(line,color='g',linewidth=4)
    127 
    128     pass
    129 
    130 # plt.show()
    131 #子图
    132 if 0:
    133     #figure()函数会产生一个指定编号为num 的图 :
    134     #plt.figure(num)
    135     '''
    136         这里,figure(1) 其实是可以省略的,因为默认情况下
    137         plt会自动地产生一幅图像,
    138         使用subplot 可以在一副图中生成多个子图,其参数为:
    139         plt.subplot(numrows,numcols,fignum)
    140         
    141         当 numrows * numcols <10  时,中间的逗号可以省略,
    142         因此,plt.subplot(211)  相当于plt.subplot(2,1,1)
    143         
    144     '''
    145     x = np.arange(-np.pi,np.pi,0.02)
    146     y = np.sin(x)
    147 
    148     plt.figure(figsize=(10,6))
    149     plt.subplot(221)
    150     plt.plot(x,y,'r-')
    151 
    152     plt.subplot(222)
    153     plt.plot(x,y*x,'g-')
    154 
    155     plt.subplot(223)
    156     plt.plot(y,x,'y-')
    157 
    158     plt.subplot(224)
    159     plt.plot(x,y*np.exp(x),'c-') #cyan  青色
    160     pass
    161 
    162 # plt.show()
    163 
    164 
    165 #excel 数据绘图
    166 df = pd.read_excel("d:/test.xlsx")
    167 if 0:
    168     print(df[:5])
    169 
    170 if 0:
    171 
    172     # plt.rcParams['font.family'] =['SimHei'] # 修改全局字体
    173     # plt.rcParams['axes.unicode_minus'] =False # 显示负号
    174     #上面修改的都是全局的 ,不建议,应当使用局部的
    175 
    176     # 绘制每个姓名的数量   的柱状图(bar chart )
    177     if 0:
    178         data = df['姓名'].value_counts()
    179         # print(data)
    180         x = data.index
    181         y = data.values
    182         plt.figure(figsize=(10,6))  #定义图片的大小
    183         plt.bar(x,y,color='c')
    184         plt.title("各个 '姓名' 的 数量 ",fontproperties='SimHei',fontsize=10)
    185         plt.xlabel("x轴",fontproperties='SimHei',fontsize=18)
    186         plt.ylabel("y轴",fontproperties='SimHei',fontsize=18)
    187 
    188         plt.tick_params(labelsize=14)
    189         plt.xticks(fontproperties ='SimHei')
    190         if 0:
    191             plt.xticks(rotation=90) #使x轴上的标签逆时针旋转90
    192 
    193 
    194         #将每个具体的数字写到柱子 上
    195         for a,b in zip(x,y):
    196             plt.text(a,b+1,b,ha='center')
    197                 #ha 是 horizontal align
    198                 #va  是 vitual align
    199 
    200         #加上网格线
    201         plt.grid()
    202 
    203 
    204         pass
    205 
    206     #绘制 每个学号的 数量 的折线图 (看趋势)
    207     if 0:
    208         data = df['学号'].value_counts()
    209         # print(data)
    210         data = data.sort_index()
    211 
    212         x = data.index
    213         y = data.values
    214 
    215         plt.plot(x,y,color = 'b')  #折线图
    216 
    217         plt.title("每个学号的数量",fontproperties='SimHei',fontsize=20)
    218         plt.xlabel("学号",fontproperties = 'SimHei',fontsize = 18)
    219         plt.ylabel("数量",fontproperties = 'SimHei',fontsize = 18)
    220 
    221         for a,b in zip(x[::5],y[::5]): #学号每隔5 画上具体数据
    222             plt.text(a,b+0.1,b)
    223 
    224         #给某一点加注释
    225         plt.annotate("这是我",fontproperties='SimHei',xy=(17096218,data[17096218]),xytext=(17096300,data[17096218]+3),
    226                      arrowprops=dict(facecolor='black',edgecolor='red')
    227                      #facecolor 是填充颜色  ,edgecolor 是边缘颜色
    228                      )
    229 
    230 
    231 
    232 
    233         pass
    234 
    235     #绘制饼图  工资  (适合类别比较少的)
    236         #饼图 Sector Graph 又名  Pie Graph
    237     if 0:
    238         '''
    239         plt.pie(
    240             x,     #x  是数据  
    241             explode=None, 
    242             labels=None,  #饼图外侧的说明文字  
    243             colors=None, 
    244             autopct=None,   #饼图内百分比的设置 
    245             pctdistance=0.6, 
    246             shadow=False,   #饼图要不要有阴影 
    247             labeldistance=1.1,
    248             startangle=None,  #起始位置的角度 
    249             radius=None
    250             ):
    251             
    252         返回值:
    253             如果没有设置autopct ,返回(patches,texts)
    254             反之,返回(patches,texts ,autotexts)
    255         '''
    256         # print(df['工资'].min())          12345.23
    257         # print(df['工资'].max())          557345.23
    258 
    259         #使用cut 离散化数据
    260         data = pd.cut(df['工资'],[12000,100000,300000,400000,560000])
    261         # print(data)
    262         if 0:
    263             print(data.value_counts())
    264             # (100000, 300000]    193
    265             # (12000, 100000]     101
    266             # (400000, 560000]     16
    267             # (300000, 400000]     10
    268             # Name: 工资, dtype: int64
    269 
    270         data = data.value_counts()
    271         y = data.values
    272         y = y/sum(y)  #就算自己不归一化,系统也会替我们进行
    273 
    274         plt.figure(figsize=(7,7))
    275         plt.title("工资的占比",fontproperties ='SimHei')
    276         patches ,l_text,p_text = plt.pie(y,labels=data.index,autopct='%.1f %%',colors='ycgr',
    277                 startangle=90,
    278                 )
    279 
    280         #根据pie 的返回值设置图中的字体
    281         #设置 p_text 图内的字体
    282         for i in p_text:
    283             i.set_size(14)
    284             i.set_color('w')
    285 
    286         #设置 l_text 图外的字体
    287         for i in l_text:
    288             i.set_size(10)
    289             i.set_color('red')
    290 
    291         #增加一个图列
    292         plt.legend()
    293 
    294         pass
    295 
    296     #绘制频率直方图  对年龄的频率绘制分布直方图
    297         #直方图 Histogram  又称质量分布图,
    298         #用来反应数据的分布情况
    299     if 1:
    300         '''
    301         plt.hist(
    302         x,  #需要计算直方图的一维数组
    303         bins=None,  #直方图的柱数,默认为 10 
    304         normaed,  #是否将得到的直方图归一化  ,默认为0  
    305         facecolor, #直方图的颜色 
    306         edgecolor,   # 直方图边框颜色 
    307         alpha ,   #透明度 
    308         histtype='bar' #直方图的类型  
    309         
    310         )
    311         返回值 :
    312         n :直方图向量  ,是否归一化由参数 normed 决定 
    313         bins :返回各个bin 的区间范围 
    314         patches :返回每个bin 里面包含的数据,是一个list  
    315         
    316         '''
    317         plt.figure(figsize=(10,6))
    318         plt.hist(df['年龄'],bins=20,edgecolor='k',alpha=0.5)
    319 
    320         pass
    321 
    322 
    323     pass
    324 plt.show()
    View Code
  • 相关阅读:
    獲得當年的周別
    動態更改GridView 的Page 頁碼的Style
    發送Mail(帶Table)
    C# DataSet和DataTable详解
    利用JS动态创建html控件并在后台实现取值
    ArrayList与string、string[]的转换代码
    js操作listbox的方法
    ASP.NET中Get和Post的用法 Request.QueryString,Request.Form,Request.Params的区别 [转]
    window.showModalDialog关闭子页面刷新父页面
    FTPClient upload & download class
  • 原文地址:https://www.cnblogs.com/zach0812/p/11567601.html
Copyright © 2020-2023  润新知