一、matplotlib包
import matplotlib.pyplot as plt
x=[1,2,3,4]
y=[1,4,9,16]
plt.plot(x,y)
plt.show()
'''color:线条颜色,值r表示红色(red)marker:点的形状,值o表示点为圆圈标记(circle marker)linestyle:线条的形状,值dashed表示用虚线连接各点'''
plt.plot(x,y,color='r',marker='o',linestyle='dashed')
'''axis:坐标轴范围语法为axis[xmin, xmax, ymin, ymax],也就是axis[x轴最小值, x轴最大值, y轴最小值, y轴最大值]'''
plt.axis([0,6,0,20])
plt.show()
如果matplotlib参入的参数只能是列表的话,这对数据处理很不利。一般,我们传入的是numpy的数组。实际上,所有参入的值内部都会转换为numpy的数组。
'''arange用于生成一个等差数组,arange([start, ]stop, [step, ]使用见文档:https://docs.scipy.org/doc/numpy/reference/generated/numpy.arange.html'''
import numpy as np
t=np.arange(0,5,0.2)
t
array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. , 1.2, 1.4, 1.6, 1.8, 2. ,
2.2, 2.4, 2.6, 2.8, 3. , 3.2, 3.4, 3.6, 3.8, 4. , 4.2,
4.4, 4.6, 4.8])
'''使用数组同时绘制多个线性'''
#线条1
x1=y1=t
'''运算符**,表示幂 - 返回x的y次幂,例如10**20表示10的20次方详细见文档《Python3运算符》:http://www.runoob.com/python3/python3-basic-operators.html'''
#线条2
x2=x1
y2=t**2
#线条3
x3=x1
y3=t**3
#使用plot绘制线条
lineList=plt.plot(x1,y1,x2,y2,x3,y3)
#用setp方法可以同时设置多个线条的属性
plt.setp(lineList,color='r')
plt.show()
print('返回的数据类型:',type(lineList))
print('数据大小:',len(lineList))
返回的数据类型:
数据大小: 3
在图上添加文本
import matplotlib
matplotlib.matplotlib_fname()
'D:\\ana\\lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc'
x=[1,2,3,4]
y=[1,4,9,16]
plt.plot(x,y)
plt.xlabel('x坐标轴')
plt.ylabel('y坐标轴')
plt.title('标题')
'''添加注释:参数名xy:箭头注释中箭头所在位置,参数名xytext:注释文本所在位置,arrowprops在xy和xytext之间绘制箭头,shrink表示注释点与注释文本之间的图标距离'''
plt.annotate('我是注释',xy=(2,5),xytext=(2,10),arrowprops=dict(facecolor='black',shrink=0.01))
plt.show()
多个图绘图
#创建画板1
fig=plt.figure(1)
#第2步:创建画纸(子图)
'''subplot()方法里面传入的三个数字前两个数字代表要生成几行几列的子图矩阵,第三个数字代表选中的子图位置subplot(211)生成一个2行1列的子图矩阵,当前是第一个子图'''
#创建画纸,并选择画纸1
#等价于ax1=fig.add_subplot(211)
ax1=plt.subplot(2,1,1)
#在画纸上绘图
plt.plot([1,2,3])
#选择画纸2
ax2=plt.subplot(2,1,2)
#在画纸2上绘图
plt.plot([4,5,6])
plt.show()
二、数据可视化:股票数据分析
互联数据获取包pandas-datareader现在已经使用不了了,所以自己导入数据。
先自己定义一个函数:计算股票涨跌幅
'''定义函数函数功能:计算股票涨跌幅=(现在股价-买入价格)/买入价格输入参数:column是收盘价这一列的数据返回数据:涨跌幅'''
def change(column):
#买入价格
buyprice=column[0]
#现在股价
#column.size是总共数据条数,序号是从0开始的,所以最后一条数据的序号是总数目-1
curprice=column[column.size-1]
#累计涨跌幅
pricechange=(curprice-buyprice)/buyprice
#判断股票是上涨,还是下跌
if pricechange>0:
print('股票累计上涨=',pricechange*100,'%')
elif pricechange==0:
print('股票累没有变化=',pricechange*100,'%')
else:
print('股票累计下跌',pricechange*100,'%')
#返回数据
return pricechange
阿里巴巴
import pandas as pd
#导入数据
filenamestr1='F:/BaiduNetdiskDownload/数据可视化/阿里巴巴2017年股票数据.xlsx'
x1=pd.ExcelFile(filenamestr1)
babadf=x1.parse('Sheet1')
babadf.head()
为了将横坐标设置成X轴坐标,将Date列设置为索引。
#重置索引,将Date设为索引
babadf.reset_index(inplace=True)
babadf.set_index('Date',inplace=True)
babadf.head()
babadf.info()
DatetimeIndex: 251 entries, 2017-01-03 to 2017-12-29
Data columns (total 7 columns):
index 251 non-null int64
Open 251 non-null float64
High 251 non-null float64
Low 251 non-null float64
Close 251 non-null float64
Adj Close 251 non-null float64
Volume 251 non-null int64
dtypes: float64(5), int64(2)
memory usage: 15.7 KB
babadf.dtypes
index int64
Open float64
High float64
Low float64
Close float64
Adj Close float64
Volume int64
dtype: object
babadf.describe()
'''累计涨幅'''
#获取收盘价Close这一列的数据
closecol1=babadf['Close']
#调用函数,获取涨跌幅
babachange=change(closecol1)
股票累计上涨= 94.6162493141 %
谷歌
filenamestr2='F:/BaiduNetdiskDownload/数据可视化/谷歌2017年股票数据.xlsx'
x2=pd.ExcelFile(filenamestr2)
goodf=x2.parse('Sheet1')
goodf.head()
goodf.reset_index(inplace=True)
goodf.set_index('Date',inplace=True)
goodf.head()
'''累计涨幅'''
#获取收盘价Close这一列的数据
closecol2=goodf['Close']
#调用函数,获取涨跌幅
goochange=change(closecol2)
股票累计上涨= 33.1060630465 %
亚马逊
filenamestr3='F:/BaiduNetdiskDownload/数据可视化/亚马逊2017年股票数据.xlsx'
x3=pd.ExcelFile(filenamestr3)
amazdf=x3.parse('Sheet1')
amazdf.head()
amazdf.reset_index(inplace=True)
amazdf.set_index('Date',inplace=True)
amazdf.head()
'''累计涨幅'''
#获取收盘价Close这一列的数据
closecol3=amazdf['Close']
#调用函数,获取涨跌幅
amazchange=change(closecol3)
股票累计上涨= 55.1700342828 %
filenamestr4='F:/BaiduNetdiskDownload/数据可视化/Facebook2017年股票数据.xlsx'
x4=pd.ExcelFile(filenamestr4)
fbdf=x4.parse('Sheet1')
fbdf.head()
fbdf.reset_index(inplace=True)
fbdf.set_index('Date',inplace=True)
fbdf.head()
'''累计涨幅'''
#获取收盘价Close这一列的数据
closecol4=fbdf['Close']
#调用函数,获取涨跌幅
fbchange=change(closecol4)
股票累计上涨= 51.0012027126 %
苹果
filenamestr5='F:/BaiduNetdiskDownload/数据可视化/苹果2017年股票数据.xlsx'
x5=pd.ExcelFile(filenamestr5)
appdf=x5.parse('Sheet1')
appdf.head()
appdf.reset_index(inplace=True)
appdf.set_index('Date',inplace=True)
appdf.head()
'''累计涨幅'''
#获取收盘价Close这一列的数据
closecol5=appdf['Close']
#调用函数,获取涨跌幅
appchange=change(closecol5)
股票累计上涨= 45.6995205217 %
腾讯
filenamestr6='F:/BaiduNetdiskDownload/数据可视化/腾讯2017年股票数据.xlsx'
x6=pd.ExcelFile(filenamestr6)
txdf=x6.parse('Sheet1')
txdf.head()
txdf.reset_index(inplace=True)
txdf.set_index('Date',inplace=True)
txdf.head()
'''累计涨幅'''
#获取收盘价Close这一列的数据
closecol6=txdf['Close']
#调用函数,获取涨跌幅
txchange=change(closecol6)
股票累计上涨= 114.361147234 %
数据可视化
%matplotlib inline
import matplotlib.pyplot as plt
折线图:绘制股票走势
babadf.plot(y='Close')
plt.xlabel('时间')
plt.ylabel('股价(美元)')
plt.title('2017年阿里巴巴股价走势')
#显示网格
plt.grid(True)
plt.show()
散点图:成交量和股价
'''我们给plot传入的横轴x坐标轴数据成交量这一列的数据,纵轴y坐标轴数据是收盘价这一列的数据,同时增加了一个参数叫kind这个值表示绘制图形的类型,这里的值等于scatter表示绘制散点图。kind取值(图形类型)参考官方文档:http://pandas.pydata.org/pandas-docs/stable/visualization.html'''
babadf.plot(x='Volume',y='Close',kind='scatter')
plt.xlabel('成交量')
plt.ylabel('股价(美元)')
plt.title('成交量和股价')
plt.grid(True)
plt.show()
#得到相关系数矩阵
babadf.corr()
#绘制谷歌的画纸1
ax1=goodf.plot(y='Close')
#通过指定画纸ax,在同一张画纸上绘图
amazdf.plot(ax=ax1,y='Close')
fbdf.plot(ax=ax1,y='Close')
appdf.plot(ax=ax1,y='Close')
babadf.plot(ax=ax1,y='Close')
txdf.plot(ax=ax1,y='Close')
plt.xlabel('时间')
plt.ylabel('股价(美元)')
plt.title('2017年GAFATA股价累计涨幅比较')
plt.grid(True)
plt.show()
'''使用label自定义图例'''
#绘制谷歌的画纸1
ax1=goodf.plot(y='Close',label='谷歌')
#通过指定画纸ax,在同一张画纸上绘图
amazdf.plot(ax=ax1,y='Close',label='亚马逊')
fbdf.plot(ax=ax1,y='Close',label='Facebook')
appdf.plot(ax=ax1,y='Close',label='苹果')
babadf.plot(ax=ax1,y='Close',label='阿里巴巴')
txdf.plot(ax=ax1,y='Close',label='腾讯')
plt.xlabel('时间')
plt.ylabel('股价(美元)')
plt.title('2017年GAFATA股价累计涨幅比较')
plt.grid(True)
plt.show()
因为谷歌和亚马逊的股价比较高,造成我们看不出其他4家公司的股票走势。 所以根据股价我们可以将这6家公司分成2组,一组是股价较高的谷歌和亚马逊。另外一组是股价较低的4家公司。
'''第1组:谷歌,亚马逊'''
#绘制谷歌的画纸2
ax2=goodf.plot(y='Close',label='谷歌')
#通过指定画纸ax,在同一张画纸上绘图
amazdf.plot(ax=ax2,y='Close',label='亚马逊')
plt.xlabel('时间')
plt.ylabel('股价(美元)')
plt.title('2017年谷歌和亚马逊股价累计涨幅比较')
plt.grid(True)
plt.show()
'''第2组:4家公司'''
#绘制Facebook的画纸3
#通过指定画纸ax,在同一张画纸上绘图
ax3=fbdf.plot(y='Close',label='Facebook')
appdf.plot(ax=ax3,y='Close',label='苹果')
babadf.plot(ax=ax3,y='Close',label='阿里巴巴')
txdf.plot(ax=ax3,y='Close',label='腾讯')
plt.xlabel('时间')
plt.ylabel('股价(美元)')
plt.title('2017年GAFATA股价累计涨幅比较')
plt.grid(True)
plt.show()
柱状图:六家公司股票的平均值
gafatameanlist=[goodf['Close'].mean(),#谷歌
amazdf['Close'].mean(),#亚马逊
fbdf['Close'].mean(),#Facebook
appdf['Close'].mean(),#苹果
babadf['Close'].mean(),#阿里巴巴
txdf['Close_dollar'].mean()#腾讯
]
gafatameanser=pd.Series(gafatameanlist,index=['谷歌',
'亚马逊',
'Facebook',
'苹果',
'阿里巴巴',
'腾讯'])
gafatameanser.plot(kind='bar',label='GAFATA')
plt.title('2017年GAFATA股价平均值')
plt.xlabel('公司名称')
plt.ylabel('股价平均值(美元)')
plt.grid(True)
plt.show()
分析结果:可以看出,仅从股票价格上来判断,亚马逊和谷歌的股票价格要远远的超过了其他四家。但是这里只是算的平均值,下面我们看下用四分位数绘制的箱线图
#存放6家公司的收盘价
closedf=pd.DataFrame()
#合并6家公司的收盘价
closedf=pd.concat([closedf,goodf['Close'],#谷歌
amazdf['Close'],#亚马逊
fbdf['Close'],#Facebook
appdf['Close'],#苹果
babadf['Close'],#阿里巴巴
txdf['Close_dollar']#腾讯
],axis=1)
closedf.columns=['谷歌','亚马逊','Facebook','Facebook','阿里巴巴','阿里巴巴']
closedf.head()
#箱线图
closedf.plot(kind='box')
plt.grid(True)
plt.show()