python数据挖掘课程 十二.Pandas、Matplotlib结合SQL语句对比图分析

        这篇文章主要讲述Python常用数据分析包Numpy、Pandas、Matplotlib结合MySQL分析数据,前一篇文章 "【python数据挖掘课程】十一.Pandas、Matplotlib结合SQL语句可视化分析" 讲述了MySQL绘图分析的好处,这篇文字进一步加深难度,对数据集进行了对比分析。
        数据分析结合SQL语句的效果真的很好,很多大神看到可能会笑话晚辈,但是如果你是数据分析的新人,那我强烈推荐,尤其是结合网络爬虫进行数据分析的。希望这篇文章对你有所帮助,如果文章中存在错误或不足之处,还请高抬贵手~

        前文推荐:
       【Python数据挖掘课程】一.安装Python及爬虫入门介绍
       【Python数据挖掘课程】二.Kmeans聚类数据分析及Anaconda介绍
       【Python数据挖掘课程】三.Kmeans聚类代码实现、作业及优化
       【Python数据挖掘课程】四.决策树DTC数据分析及鸢尾数据集分析
       【Python数据挖掘课程】五.线性回归知识及预测糖尿病实例
       【Python数据挖掘课程】六.Numpy、Pandas和Matplotlib包基础知识
       【Python数据挖掘课程】七.PCA降维操作及subplot子图绘制
       【Python数据挖掘课程】八.关联规则挖掘及Apriori实现购物推荐
       【Python数据挖掘课程】九.回归模型LinearRegression简单分析氧化物数据
       【python数据挖掘课程】十.Pandas、Matplotlib、PCA绘图实用代码补充
       【python数据挖掘课程】十一.Pandas、Matplotlib结合SQL语句可视化分析



一. 直方图四图对比

        数据库如下所示,包括URL、作者、标题、摘要、日期、阅读量和评论数等。


            
        运行结果如下所示,其中绘制多个图的核心代码为:
        p1 = plt.subplot(221)
        plt.bar(ind, num1, width, color='b', label='sum num')   
        plt.sca(p1)


        完整代码如下:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. # coding=utf-8  
  2. ''''' 
  3. ' 这篇代码主要讲述获取MySQL中数据,再进行简单的统计 
  4. ' 统计采用SQL语句进行 
  5. '''  
  6.   
  7. import matplotlib.pyplot as plt  
  8. import matplotlib  
  9. import pandas as pd  
  10. import numpy as np  
  11. import pylab  
  12. import MySQLdb  
  13. from pylab import *  
  14.   
  15. # 根据SQL语句输出24小时的柱状图  
  16. try:  
  17.     conn = MySQLdb.connect(host='localhost',user='root',  
  18.                          passwd='123456',port=3306, db='test01')  
  19.     cur = conn.cursor() #数据库游标  
  20.   
  21.     #防止报错:UnicodeEncodeError: 'latin-1' codec can't encode character  
  22.     conn.set_character_set('utf8')  
  23.     cur.execute('SET NAMES utf8;')  
  24.     cur.execute('SET CHARACTER SET utf8;')  
  25.     cur.execute('SET character_set_connection=utf8;')  
  26.       
  27.   
  28.     #################################################  
  29.     # 2014年  
  30.     #################################################  
  31.     sql = '''''select MONTH(FBTime) as mm, count(*) as cnt from csdn_blog 
  32.             where DATE_FORMAT(FBTime,'%Y')='2014' group by mm;'''  
  33.     cur.execute(sql)  
  34.     result = cur.fetchall() #获取结果复制给result  
  35.     hour1 = [n[0for n in result]  
  36.     print hour1  
  37.     num1 = [n[1for n in result]  
  38.     print num1  
  39.   
  40.     N =  12  
  41.     ind = np.arange(N)  #赋值0-11    
  42.     width=0.35  
  43.     p1 = plt.subplot(221)  
  44.     plt.bar(ind, num1, width, color='b', label='sum num')     
  45.     #设置底部名称      
  46.     plt.xticks(ind+width/2, hour1, rotation=40#旋转40度  
  47.     for i in range(12):   #中心底部翻转90度  
  48.         plt.text(i, num1[i], str(num1[i]),  
  49.                  ha='center', va='bottom', rotation=45)   
  50.     plt.title('2014 Number-12Month')      
  51.     plt.sca(p1)  
  52.   
  53.   
  54.     #################################################  
  55.     # 2015年  
  56.     #################################################  
  57.     sql = '''''select MONTH(FBTime) as mm, count(*) as cnt from csdn_blog 
  58.             where DATE_FORMAT(FBTime,'%Y')='2015' group by mm;'''  
  59.     cur.execute(sql)  
  60.     result = cur.fetchall()          
  61.     hour1 = [n[0for n in result]  
  62.     print hour1  
  63.     num1 = [n[1for n in result]  
  64.     print num1  
  65.       
  66.     N =  12  
  67.     ind = np.arange(N)  #赋值0-11    
  68.     width=0.35  
  69.     p2 = plt.subplot(222)  
  70.     plt.bar(ind, num1, width, color='r', label='sum num')     
  71.     #设置底部名称      
  72.     plt.xticks(ind+width/2, hour1, rotation=40#旋转40度  
  73.     for i in range(12):   #中心底部翻转90度  
  74.         plt.text(i, num1[i], str(num1[i]),  
  75.                  ha='center', va='bottom', rotation=45)   
  76.     plt.title('2015 Number-12Month')      
  77.     plt.sca(p2)  
  78.   
  79.   
  80.     #################################################  
  81.     # 2016年  
  82.     #################################################  
  83.     sql = '''''select MONTH(FBTime) as mm, count(*) as cnt from csdn_blog 
  84.             where DATE_FORMAT(FBTime,'%Y')='2016' group by mm;'''  
  85.     cur.execute(sql)  
  86.     result = cur.fetchall()          
  87.     hour1 = [n[0for n in result]  
  88.     print hour1  
  89.     num1 = [n[1for n in result]  
  90.     print num1  
  91.   
  92.     N =  12  
  93.     ind = np.arange(N)  #赋值0-11   
  94.     width=0.35  
  95.     p3 = plt.subplot(223)  
  96.     plt.bar(ind, num1, width, color='g', label='sum num')     
  97.     #设置底部名称      
  98.     plt.xticks(ind+width/2, hour1, rotation=40#旋转40度  
  99.     for i in range(12):   #中心底部翻转90度  
  100.         plt.text(i, num1[i], str(num1[i]),  
  101.                  ha='center', va='bottom', rotation=45)   
  102.     plt.title('2016 Number-12Month')      
  103.     plt.sca(p3)  
  104.   
  105.       
  106.     #################################################  
  107.     # 所有年份数据对比  
  108.     #################################################  
  109.     sql = '''''select MONTH(FBTime) as mm, count(*) as cnt from csdn_blog group by mm;'''  
  110.     cur.execute(sql)  
  111.     result = cur.fetchall()       
  112.     hour1 = [n[0for n in result]  
  113.     print hour1  
  114.     num1 = [n[1for n in result]  
  115.     print num1  
  116.   
  117.     N =  12  
  118.     ind = np.arange(N)  #赋值0-11    
  119.     width=0.35  
  120.     p4 = plt.subplot(224)  
  121.     plt.bar(ind, num1, width, color='y', label='sum num')     
  122.     #设置底部名称      
  123.     plt.xticks(ind+width/2, hour1, rotation=40#旋转40度  
  124.     for i in range(12):   #中心底部翻转90度  
  125.         plt.text(i, num1[i], str(num1[i]),  
  126.                  ha='center', va='bottom', rotation=45)   
  127.     plt.title('All Year Number-12Month')      
  128.     plt.sca(p4)  
  129.   
  130.     plt.savefig('ttt.png',dpi=400)      
  131.     plt.show()  
  132.   
  133. #异常处理  
  134. except MySQLdb.Error,e:  
  135.     print "Mysql Error %d: %s" % (e.args[0], e.args[1])  
  136. finally:  
  137.     cur.close()  
  138.     conn.commit()    
  139.     conn.close()  



二. Area Plot图对比

        运行效果如下所示,核心代码如下:
        data = np.array([num1, num2, num3, num4])
        d = data.T #转置 12*4
        df = DataFrame(d, index=hour1, columns=['All','2014', '2015', '2016'])
        df.plot(kind='area', alpha=0.2) #设置颜色 透明度
        plt.savefig('csdn.png',dpi=400) 
        plt.show()

        其中需要将num1~num4合并为[12,4]数组,同时转换为array,再转置绘图。index是设置X轴时间,columns是设置每行数据对应的值。kind='area'设置Area Plot图,还有 'bar'(柱状图)、'barh'(柱状图-纵向)、'scatter'(散点图)、'pie'(饼图)。


        该图会将数据划分为等级梯度,基本趋势相同。
        完整代码如下所示:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. # coding=utf-8  
  2. ''''' 
  3. ' 这篇代码主要讲述获取MySQL中数据,再进行简单的统计 
  4. ' 统计采用SQL语句进行 By:Eastmount CSDN 
  5. '''  
  6.   
  7. import matplotlib.pyplot as plt  
  8. import matplotlib  
  9. import pandas as pd  
  10. import numpy as np  
  11. import MySQLdb  
  12. from pandas import *  
  13.   
  14. try:  
  15.     conn = MySQLdb.connect(host='localhost',user='root',  
  16.                          passwd='123456',port=3306, db='test01')  
  17.     cur = conn.cursor() #数据库游标  
  18.   
  19.     #防止报错:UnicodeEncodeError: 'latin-1' codec can't encode character  
  20.     conn.set_character_set('utf8')  
  21.     cur.execute('SET NAMES utf8;')  
  22.     cur.execute('SET CHARACTER SET utf8;')  
  23.     cur.execute('SET character_set_connection=utf8;')  
  24.   
  25.     #所有博客数  
  26.     sql = '''''select MONTH(FBTime) as mm, count(*) as cnt from csdn_blog 
  27.              group by mm;'''  
  28.     cur.execute(sql)  
  29.     result = cur.fetchall()        #获取结果复制给result  
  30.     hour1 = [n[0for n in result]  
  31.     print hour1  
  32.     num1 = [n[1for n in result]  
  33.     print num1  
  34.   
  35.     #2014年博客数  
  36.     sql = '''''select MONTH(FBTime) as mm, count(*) as cnt from csdn_blog 
  37.              where DATE_FORMAT(FBTime,'%Y')='2014' group by mm;'''  
  38.     cur.execute(sql)  
  39.     result = cur.fetchall()          
  40.     num2 = [n[1for n in result]  
  41.     print num2  
  42.   
  43.     #2015年博客数  
  44.     sql = '''''select MONTH(FBTime) as mm, count(*) as cnt from csdn_blog 
  45.              where DATE_FORMAT(FBTime,'%Y')='2015' group by mm;'''  
  46.     cur.execute(sql)  
  47.     result = cur.fetchall()         
  48.     num3 = [n[1for n in result]  
  49.     print num3  
  50.   
  51.     #2016年博客数  
  52.     sql = '''''select MONTH(FBTime) as mm, count(*) as cnt from csdn_blog 
  53.              where DATE_FORMAT(FBTime,'%Y')='2016' group by mm;'''  
  54.     cur.execute(sql)  
  55.     result = cur.fetchall()         
  56.     num4 = [n[1for n in result]  
  57.     print num4  
  58.   
  59.     #重点: 数据整合 [12,4]  
  60.     data = np.array([num1, num2, num3, num4])  
  61.     print data  
  62.     d = data.T #转置  
  63.     print d  
  64.     df = DataFrame(d, index=hour1, columns=['All','2014''2015''2016'])  
  65.     df.plot(kind='area', alpha=0.2#设置颜色 透明度  
  66.     plt.title('Arae Plot Blog-Month')   
  67.     plt.savefig('csdn.png',dpi=400)   
  68.     plt.show()  
  69.   
  70. #异常处理  
  71. except MySQLdb.Error,e:  
  72.     print "Mysql Error %d: %s" % (e.args[0], e.args[1])  
  73. finally:  
  74.     cur.close()  
  75.     conn.commit()    
  76.     conn.close()  
  77.       



三. MySQL语句获取星期信息

        MySQL通过日期获取星期的语句如下:

[sql]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. select  now(), case dayofweek(now())    
  2.     when 1 then '星期日'   
  3.     when 2 then '星期一'   
  4.     when 3 then '星期二'   
  5.     when 4 then '星期三'   
  6.     when 5 then '星期四'   
  7.     when 6 then '星期五'   
  8.     when 7 then '星期六' end as 'week'    
  9. from dual;  
         输出如下图所示:
         Python对应的代码如下,获取总的博客星期分布:
[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. # coding=utf-8  
  2. ''''' 
  3. ' 这篇代码主要讲述获取MySQL中数据,再进行简单的统计 
  4. ' 统计采用SQL语句进行 By:Eastmount CSDN 
  5. '''  
  6.   
  7. import matplotlib.pyplot as plt  
  8. import matplotlib  
  9. import pandas as pd  
  10. import numpy as np  
  11. import MySQLdb  
  12. from pandas import *  
  13.   
  14. try:  
  15.     conn = MySQLdb.connect(host='localhost',user='root',  
  16.                          passwd='123456',port=3306, db='test01')  
  17.     cur = conn.cursor() #数据库游标  
  18.   
  19.     #防止报错:UnicodeEncodeError: 'latin-1' codec can't encode character  
  20.     conn.set_character_set('utf8')  
  21.     cur.execute('SET NAMES utf8;')  
  22.     cur.execute('SET CHARACTER SET utf8;')  
  23.     cur.execute('SET character_set_connection=utf8;')  
  24.     sql = '''''select   
  25.             COUNT(case dayofweek(FBTime)  when 1 then 1 end) AS '星期日', 
  26.             COUNT(case dayofweek(FBTime)  when 2 then 1 end) AS '星期一', 
  27.             COUNT(case dayofweek(FBTime)  when 3 then 1 end) AS '星期二', 
  28.             COUNT(case dayofweek(FBTime)  when 4 then 1 end) AS '星期三', 
  29.             COUNT(case dayofweek(FBTime)  when 5 then 1 end) AS '星期四', 
  30.             COUNT(case dayofweek(FBTime)  when 6 then 1 end) AS '星期五', 
  31.             COUNT(case dayofweek(FBTime)  when 7 then 1 end) AS '星期六' 
  32.             from csdn_blog; 
  33.           '''  
  34.     cur.execute(sql)  
  35.     result = cur.fetchall()       
  36.     print result  
  37.     #((31704L, 43081L, 42670L, 43550L, 41270L, 39164L, 29931L),)  
  38.     name = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']  
  39.     #转换为numpy数组  
  40.     data = np.array(result)  
  41.     print data  
  42.     d = data.T #转置  
  43.     print d  
  44.   
  45.     matplotlib.style.use('ggplot')  
  46.     df=DataFrame(d, index=name,columns=['Nums'])  
  47.     df.plot(kind='bar')  
  48.     plt.title('All Year Blog-Week')      
  49.     plt.xlabel('Week')  
  50.     plt.ylabel('The number of blog')  
  51.     plt.savefig('01csdn.png',dpi=400)  
  52.     plt.show()  
  53.   
  54. #异常处理  
  55. except MySQLdb.Error,e:  
  56.     print "Mysql Error %d: %s" % (e.args[0], e.args[1])  
  57. finally:  
  58.     cur.close()  
  59.     conn.commit()    
  60.     conn.close()  
  61.          
         运行结果如下所示:



四. 星期数据柱状图及折线图对比

        下面获取四年的数据进行对比,代码如下所示:

        核心代码如下,注意三个一维数组转换为num[7][3]二维数组的方法。
        data = np.random.rand(7,3)
        print data
        i = 0
        while i<7:
            data[i][0] = d1[i]
            data[i][1] = d2[i]
            data[i][2] = d3[i]
            i = i + 1    
        matplotlib.style.use('ggplot')
        #数据[7,3]数组 name为星期 columns对应年份
        df=DataFrame(data, index=name, columns=['2008','2011','2016'])
        df.plot(kind='bar')   
        plt.show()


        完整代码为:

[python]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. # coding=utf-8  
  2. ''''' 
  3. ' 这篇代码主要讲述获取MySQL中数据,再进行简单的统计 
  4. ' 统计采用SQL语句进行 By:Eastmount CSDN 杨秀璋 
  5. '''  
  6.   
  7. import matplotlib.pyplot as plt  
  8. import matplotlib  
  9. import pandas as pd  
  10. import numpy as np  
  11. import MySQLdb  
  12. from pandas import *  
  13.   
  14. try:  
  15.     conn = MySQLdb.connect(host='localhost',user='root',  
  16.                          passwd='123456',port=3306, db='test01')  
  17.     cur = conn.cursor() #数据库游标  
  18.   
  19.     #防止报错:UnicodeEncodeError: 'latin-1' codec can't encode character  
  20.     conn.set_character_set('utf8')  
  21.     cur.execute('SET NAMES utf8;')  
  22.     cur.execute('SET CHARACTER SET utf8;')  
  23.     cur.execute('SET character_set_connection=utf8;')  
  24.     sql = '''''select   
  25.             COUNT(case dayofweek(FBTime)  when 1 then 1 end) AS '星期日', 
  26.             COUNT(case dayofweek(FBTime)  when 2 then 1 end) AS '星期一', 
  27.             COUNT(case dayofweek(FBTime)  when 3 then 1 end) AS '星期二', 
  28.             COUNT(case dayofweek(FBTime)  when 4 then 1 end) AS '星期三', 
  29.             COUNT(case dayofweek(FBTime)  when 5 then 1 end) AS '星期四', 
  30.             COUNT(case dayofweek(FBTime)  when 6 then 1 end) AS '星期五', 
  31.             COUNT(case dayofweek(FBTime)  when 7 then 1 end) AS '星期六' 
  32.             from csdn_blog where DATE_FORMAT(FBTime,'%Y')='2008'; 
  33.           '''  
  34.     cur.execute(sql)  
  35.     result1 = cur.fetchall()          
  36.     print result1  
  37.     name = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']  
  38.     data = np.array(result1)  
  39.     d1 = data.T #转置  
  40.     print d1  
  41.   
  42.   
  43.     sql = '''''select   
  44.             COUNT(case dayofweek(FBTime)  when 1 then 1 end) AS '星期日', 
  45.             COUNT(case dayofweek(FBTime)  when 2 then 1 end) AS '星期一', 
  46.             COUNT(case dayofweek(FBTime)  when 3 then 1 end) AS '星期二', 
  47.             COUNT(case dayofweek(FBTime)  when 4 then 1 end) AS '星期三', 
  48.             COUNT(case dayofweek(FBTime)  when 5 then 1 end) AS '星期四', 
  49.             COUNT(case dayofweek(FBTime)  when 6 then 1 end) AS '星期五', 
  50.             COUNT(case dayofweek(FBTime)  when 7 then 1 end) AS '星期六' 
  51.             from csdn_blog where DATE_FORMAT(FBTime,'%Y')='2011'; 
  52.           '''  
  53.     cur.execute(sql)  
  54.     result2 = cur.fetchall()          
  55.     data = np.array(result2)  
  56.     d2 = data.T #转置  
  57.     print d2  
  58.   
  59.   
  60.     sql = '''''select   
  61.             COUNT(case dayofweek(FBTime)  when 1 then 1 end) AS '星期日', 
  62.             COUNT(case dayofweek(FBTime)  when 2 then 1 end) AS '星期一', 
  63.             COUNT(case dayofweek(FBTime)  when 3 then 1 end) AS '星期二', 
  64.             COUNT(case dayofweek(FBTime)  when 4 then 1 end) AS '星期三', 
  65.             COUNT(case dayofweek(FBTime)  when 5 then 1 end) AS '星期四', 
  66.             COUNT(case dayofweek(FBTime)  when 6 then 1 end) AS '星期五', 
  67.             COUNT(case dayofweek(FBTime)  when 7 then 1 end) AS '星期六' 
  68.             from csdn_blog where DATE_FORMAT(FBTime,'%Y')='2016'; 
  69.           '''  
  70.     cur.execute(sql)  
  71.     result3 = cur.fetchall()         
  72.     data = np.array(result3)  
  73.     print type(result3),type(data)  
  74.     d3 = data.T #转置  
  75.     print d3  
  76.   
  77.   
  78.     #SQL语句获取3个数组,采用循环复制到一个[7][3]的二维数组中  
  79.     data = np.random.rand(7,3)  
  80.     print data  
  81.     i = 0  
  82.     while i<7:  
  83.         data[i][0] = d1[i]  
  84.         data[i][1] = d2[i]  
  85.         data[i][2] = d3[i]  
  86.         i = i + 1  
  87.   
  88.     print data  
  89.     print type(data)  
  90.   
  91.     #绘图  
  92.     matplotlib.style.use('ggplot')  
  93.     #数据[7,3]数组 name为星期 columns对应年份  
  94.     df=DataFrame(data, index=name, columns=['2008','2011','2016'])  
  95.     df.plot(kind='bar')     
  96.     plt.title('Comparison Chart Blog-Week')      
  97.     plt.xlabel('Week')  
  98.     plt.ylabel('The number of blog')  
  99.     plt.savefig('03csdn.png', dpi=400)  
  100.     plt.show()  
  101.   
  102.   
  103.   
  104. #异常处理  
  105. except MySQLdb.Error,e:  
  106.     print "Mysql Error %d: %s" % (e.args[0], e.args[1])  
  107. finally:  
  108.     cur.close()  
  109.     conn.commit()    
  110.     conn.close()  
  111.         
        其中将代码 "df.plot(kind='bar')" 修改为  "df.plot()" 即为折线图。

 

         讲到这里,通过Pandas、Matplotlib、Numpy结合MySQL可视化分析,并且进阶对比图片函数的分析过程已经讲完了,后面会结合SQL数据库做一些词云WordCloud、颜色图、Power-low图等分析。

       希望文章对你有所帮助,尤其是结合数据库做数据分析的人。还是那句话,如果刚好需要这部分知识,你就会觉得非常有帮助,否则只是觉得好玩,这也是在线笔记的作用。如果文章中存在不足或错误的地方,还请海涵~

        最近可能有些事情需要发生,我都需要平常心对待,真的好喜欢教学,认真教学生些东西,但是又觉得 "教优则 仕" 也有道理!做自己,为每一个自己的学生付出我所能做的所有。同时,真的心疼绿幺,但是有她陪着真的感觉两个人能克服一切,心安娜美~

        可视化推荐下面的文章:
        [转] 使用python绘制简单的图表 - 初雪之音 (强推)
        利用Python进行数据分析——绘图和可视化(八) (强推)
        用 Seaborn 画出好看的分布图(Python) [强推]
        10分钟python图表绘制 | seaborn入门(一):distplot与kdeplot
        python数据可视化(matplotlib,pandas绘图,散点图,柱状图,折线图,箱线图)
        Python之numpy教程(三):转置、乘积、通用函数
        


        (By:Eastmount 2017-03-20 晚上7点  
http://blog.csdn.net/eastmount/ )

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值