簡介
本文主要介紹了讀取mysql中的資料,将其儲存至numpy和pandas中,通過matplotlib進行可視化資料分析。
一、環境搭建
使用anaconda搭建科學計算環境,并安裝相關軟體包。
conda create -n science python= numpy pandas matplotlib
source activate science
pip install mysql-python
二、生成2014每月資料柱狀圖
mysql> select Y,M,Sale from Yield where proptype= and tjtype= and datatype= and Y=;
+------+----+----------------+
| Y | M | Sale |
+------+----+----------------+
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
+------+----+----------------+
#!/usr/local/miniconda2/envs/science/bin/python
#-*- coding: utf-8 -*-
import MySQLdb
import numpy as np
import matplotlib.pyplot as plt
db=MySQLdb.connect(host="10.10.89.11",user='test',passwd="test",port=,db="dbtest")
cursor=db.cursor()
sql="select Y,M,Sale from Yield where proptype=11 and tjtype=1 and datatype=1 and Y=2014"
cursor.execute(sql)
result=cursor.fetchall()
#定義結構數組的資料類型
qushi=np.dtype([('Y','i2'),('M','i2'),('Sale','f4')])
data=np.fromiter(result,dtype=qushi,count=-)
#字型設定
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['simhei']
plt.rcParams['axes.unicode_minus'] = False
#柱狀圖
plt.bar(data['M'],data['Sale'],align='center')
plt.title(u'2014趨勢')
plt.xlabel(u'月份')
plt.ylabel(u'價格')
plt.xticks(data['M'])
plt.show()
db.close()
![](https://img.laitimes.com/img/9ZDMuAjOiMmIsIjOiQnIsICdzFWRoRXdvN1LclHdpZXYyd2LcBzNvwVZ2x2bzNXak9CX90TQNNkRrFlQKBTSvwFbslmZvwFMwQzLcVmepNHdu9mZvwFVywUNMZTY18CX052bm9CX90zdORzaU10akJjW1Z0VlZXUYpVd1kmYr50MZV3YyI2cKJDT29GRjBjUIF2LcRHelR3LcJzLctmch1mclRXY39DO1gTN1gDM5ATMzMDM3EDMy8CX0Vmbu4GZzNmLn9Gbi1yZtl2Lc9CX6MHc0RHaiojIsJye.jpg)
要點:
1.由于從mysql讀取的資料字段的資料類型不同,是以需要對每個字段重新定義。在此我們先定義了一個qushi的dtype對象,通過其字典參數描述結構類型的各個字段。
2.從mysql讀取的資料為元組,需要通過fromiter函數從任何可疊代對象建構一個ndarray對象,傳回一個新的一維數組。
3.字型設定
matplotlib預設無法顯示中文,按代碼中設定若報錯”UserWarning: findfont: Font family [u’sans-serif’] not found”
需要将下載下傳的simhei.tty字型放到”/usr/local/miniconda2/envs/science/lib/python2.7/site-packages/matplotlib/mpl-data/fonts/tty”目錄下;若有字型但還是顯示小方塊,一般是沒有删除/root/.cache/matplotlib 的緩沖目錄
或用如下設定
#中文字型解決
ziti = path.join(mulu, 'simsun.ttc')
font = FontProperties(fname=ziti, size=)
plt.title(u'2014趨勢',fontproperties=font)
plt.xlabel(u'月份',fontproperties=font)
plt.ylabel(u'價格',fontproperties=font)
三.生成2013年和2014年月份對比圖
Series和DataFrame都有一個用于生成各類圖示的plot方法,預設情況下,他們所生成的是線型圖,該Series的索引會被傳給matplotlib,并用于繪制x軸。
在生成的線型圖的代碼中加上kind=’bar’(垂直樹狀圖)或 kind=’barch’(水準柱狀圖)即可生成柱狀圖,此時,Series和DataFrame的索引将會被用作X或Y的刻度。
注意:繪制線型圖或柱狀圖需要編排series和dataframe的格式如下:
#合并并重新指定index後的新dataframe,否則index從0開始與月份不對應
#print new11
data data
m1
因為對于DataFrame,柱狀圖會将每一行的值分為一組。但是我們從mysql讀取的資料不是這樣的,是以我們需要通過dataframe的concat來合并,并修改index才能得到上面的格式。
#!/usr/local/miniconda2/envs/science/bin/python
#-*- coding: utf-8 -*-
import pandas as pd
import matplotlib.pyplot as plt
import MySQLdb
db=MySQLdb.connect(host="10.10.89.11",user='test',passwd="test",port=,db="dbtest")
sql2014="select Y,M as 'm1',Sale as '2014data' from Yield where proptype=11 and tjtype=1 and datatype=1 and Y=2014"
sql2013="select Y,M,Sale as '2013data' from Yield where proptype=11 and tjtype=1 and datatype=1 and Y=2013"
#通過read_sql讀取資料
df2014=pd.read_sql(sql2014,con=db)
df2013=pd.read_sql(sql2013,con=db)
#橫向合并dataframe
new=pd.concat([df2014,df2013],axis=)
#擷取相關列
new_df=new[["m1","2013data","2014data"]]
#将m1列指定為index,否則index預設為0-12
new11=new_df.set_index("m1")
plt.rcParams['font.family'] = 'sans-serif'
plt.rcParams['font.sans-serif'] = ['simhei']
plt.rcParams['axes.unicode_minus'] = False
#線型圖
#new11.plot()
#柱狀圖
new11.plot(kind='bar')
plt.xlabel(u"月份")
plt.ylabel(u"銷售資料")
plt.show()
db.close
要點:
1.read_sql的參數index_col制定某列為索引列,通過此設定,我們concat後就不用set_index了。
df2014=pd.read_sql(sql2014,con=db,index_col='M')
df2013=pd.read_sql(sql2013,con=db,index_col='M')
new=pd.concat([df2014,df2013],axis=)
new_df=new[["2013data","2014data"]]
print new_df
#列印資料
data data
M