import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
1 读表
uni=pd.read_table('/Users/anita/k3.txt')
uni.dtypes #查看每一列的数据类型
qsrank object schoolname object qsstars float64 overall float64 academic float64 employer float64 faculty float64 international float64 internationalstudents float64 citations float64 arts float64 engineering float64 life float64 natural float64 social float64 dtype: object
画图
画图 matplotlib.pyplot 它与matlab运行起来十分相似
http://www.cnblogs.com/zhizhan/p/5615947.html
import matplotlib.pyplot as plt
plt.plot(range(10))
[
import numpy as np
import matplotlib.pyplot as plt
x=np.arange(-np.pi,np.pi,0.01)
y=np.sin(x)
plt.plot(x,y,'g')
plt.show()
设置坐标区间
plt.axis([-6,6,-10,10]) #设置横坐标轴的区间为[-6,6],纵坐标的区间为[-10,10]
[-6, 6, -10, 10] 修改坐标区间
plt.title("a strait line") #设置图表标题
x=np.arange(-5,5,0.01) #原本x的区间是[-5,5]
y=x**3
plt.xlabel("x value") #设置坐标轴名称
plt.ylabel("y value")
plt.xlim(-6,6) #现在把区间改为[-6,6],同理ylim可以修改y轴的区间
plt.plot(x,y,'m')
plt.grid(True) #这句话可要可不要,有了True的话,就可以显示网格线
plt.savefig("demo.jpg") #保存图表
plt.show()
设置线条样式
* 虚线 –
* 虚线加点 -.
* 小点点 :
x=np.arange(-5,5,0.01) #原本x的区间是[-5,5]
y=x**3
plt.plot(x,y,'--') #'--'表示绘制的是虚线
plt.show()
画散点图
import numpy as np
import matplotlib.pyplot as plt
plt.title("a strait line") #设置图表标题
x=[-1,1,3,4,5]
y=[1,3,4,5,6]
plt.plot(x,y,'or') # 'o'表示绘制圆圈散点图,注:如果是‘or’,那就是红色的散点图
plt.show()
设置散点的样式
圆圈: o, 正方形:s, 星号:*, 六边形:h, 六边形:H, 加号:+, 菱形:D, 瘦菱形:d
同时设置多种样式
1)散点图
x=[-1,1,3,4,5]
y=[1,3,4,5,6]
plt.plot(x,y,'*r') # '*'表示化星星,‘r’表示颜色是红色,‘*r’表示红色的星星
plt.show()
2)折线图(同样的代码)
x=[-1,1,3,4,5]
y=[1,3,4,5,6]
plt.plot(x,y,'--')
plt.show()
添加注释annotate
x=[-1,1,3,4,5]
y=[1,3,4,5,6]
plt.plot(x,y,'--')
plt.annotate('local max', xy=(2, 2), xytext=(3, 3),arrowprops=dict(facecolor='black', shrink=0.001))
plt.show()
设置线条颜色
* ‘b‘ blue
* ‘g’ green
* ‘r’ red
* ‘c’ cyan
* ‘m’ magenta
* ‘y’ yellow
* ‘k’ black
* ‘w’ whit
在一个坐标轴中绘制多个函数的线条
x1 = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
x2 = [1, 2, 4, 6, 8]
y2 = [2, 4, 8, 12, 16]
plt.plot(x1, y1, 'r')
plt.plot(x2, y2, 'g')
plt.show()
设置图例
plt.legend(label,loc=0,ncol=1)
loc(图例位置): 0表示自适应,1表示右上,2表示左上,3表示左下,4表示右下
nloc表示图例的行数
x1 = [1, 2, 3, 4, 5]
y1 = [1, 4, 9, 16, 25]
x2 = [1, 2, 4, 6, 8]
y2 = [2, 4, 8, 12, 16]
plt.plot(x1, y1, 'r',label='line1')
plt.plot(x2, y2, 'g',label='line2')
plt.legend(label,loc=1,ncol=1)
plt.show()
直方图
import numpy as np
import pylab as plt
data = np.random.normal(5.0, 3.0, 1000)
plt.hist(data, color='r',histtype='stepfilled') # 设置不要框线
plt.show()
设置直方图的宽度 bins, 图形中支持latex公式编辑
import numpy as np
import pylab as plt
plt.title(r'$\alpha > \beta$')
data = np.random.normal(5.0, 3.0, 1000)
bins = np.arange(-5., 16., 1.) #横坐标区间为[-5,16],间距为1
plt.hist(data,bins,color='r',histtype='stepfilled') # 设置不要框线
plt.show()
同一画板上绘制多幅子图
matplotlib下, 一个 Figure 对象可以包含多个子图(Axes), 可以使用 subplot() 快速绘制, 其调用形式如下 :
subplot(numRows, numCols, plotNum)
图表的整个绘图区域被分成 numRows 行和 numCols 列
plotNum 参数指定创建的 Axes 对象所在的区域
import numpy as np
import pylab as plt
def f(t):
return np.exp(-t) * np.cos(2 * np.pi * t)
t1 = np.arange(0, 5, 0.1)
t2 = np.arange(0, 5, 0.02)
plt.subplot(221)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'r--') #一个图中画了两条线
plt.subplot(222)
plt.plot(t2, np.cos(2 * np.pi * t2), 'r--')
plt.subplot(223)
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])#这个图占了两个图的位置
plt.subplot(2,2,4)
plt.hist(np.random.randn(100),bins=20, color='m',alpha=0.3) #alpha设置透明度
plt.show()
面向对象画图
matplotlib API包含有三层,Artist层处理所有的高层结构,例如处理图表、文字和曲线等的绘制和布局。通常我们只和Artist打交道,而不需要关心底层的绘制细节。 直接使用Artists创建图表的标准流程如下:
• 创建Figure对象
• 用Figure对象创建一个或者多个Axes或者Subplot对象
• 调用Axies等对象的方法创建各种简单类型的Artists
import matplotlib.pyplot as plt
X1 = range(0, 50)
Y1 = [num**2 for num in X1] # y = x^2
X2 = [0, 1000]
Y2 = [0, 1000] # y = x
Fig = plt.figure(figsize=(8,4)) # 第一层:Create a `figure' instance
Ax = Fig.add_subplot(111) # 第二层:Create a `axes' instance in the figure
Ax.plot(X1, Y1, X2, Y2) # 第三层:Create a Line2D instance in the axes
Fig.show()
Fig.savefig("test.pdf")
import matplotlib.pyplot as plt
X1 = range(0, 50)
Y1 = [num**2 for num in X1] # y = x^2
X2 = [0, 1000]
Y2 = [0, 1000] # y = x
Fig = plt.figure(figsize=(8,4)) # 第一层:Create a `figure' instance
Ax1 = Fig.add_subplot(211) # 第二层:Create a `axes' instance in the figure
Ax1.plot(X1, Y1, X2, Y2) # 第三层:Create a Line2D instance in the axes
Ax2 = Fig.add_subplot(212) # 第二层:Create a `axes' instance in the figure
Ax2.plot(X1, Y1)
Fig.show()
import numpy as np
import matplotlib.pyplot as plt
plt.figure(1) # 创建图表1
plt.figure(2) # 创建图表2
ax1 = plt.subplot(211) # 在图表2中创建子图1
ax2 = plt.subplot(212) # 在图表2中创建子图2
x = np.linspace(0, 3, 100)
for i in range(5):
plt.figure(1) #❶ # 选择图表1
plt.plot(x, np.exp(i*x/3))
plt.sca(ax1) #❷ # 选择图表2的子图1
plt.plot(x, np.sin(i*x))
plt.sca(ax2) # 选择图表2的子图2
plt.plot(x, np.cos(i*x))
plt.show()
fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
plt.plot(np.random.randn(50).cumsum(),'k--')
ax1.hist(np.random.randn(100),bins=20, color='k',alpha=0.3)
ax2.scatter(np.arange(30), np.arange(30)+ 3* np.random.randn(30))
plt.show()
#cumsum(),其中0代表列的计算,1代表行的计算,即对列和行分别累积求和。
#cumprod(1) 表示对行求积
fig = plt.figure()
plt.axis([0, 10,])
plt.axis(np.random.randn(50).cumsum(),'k--')
plt.axes(np.random.randn(100),bins=20, color='k',alpha=0.3)
plt.axes(np.arange(30), np.arange(30)+ 3* np.random.randn(30))
plt.show()
#cumsum(),其中0代表列的计算,1代表行的计算,即对列和行分别累积求和。
#cumprod(1) 表示对行求积
plot功能,很强大,绘出来的图形很好看
import numpy as np
import matplotlib.pyplot as plt
plt.style.use= 'default'
ts = pd.Series(np.random.randn(1000), index=pd.date_range('1/1/2000', periods=1000))
ts = ts.cumsum()
ts.plot()
df = pd.DataFrame(np.random.randn(1000, 4), index=ts.index,columns=list('ABCD'))
df = df.cumsum()
#plt.figure()
df.plot()
df3 = pd.DataFrame(np.random.randn(1000, 2), columns=['B', 'C']).cumsum()
df3['A'] = pd.Series(list(range(len(df))))
df3.plot(x='A', y='B')
df.ix[5]
A | B | C | D | |
---|---|---|---|---|
2000-01-01 | 0.459922 | -1.107027 | 1.134867 | 0.166950 |
2000-01-02 | 2.346380 | -2.231107 | 1.881184 | 1.231315 |
2000-01-03 | 3.395658 | -0.939746 | -2.178430 | 0.909716 |
2000-01-04 | 3.153648 | -1.494069 | -2.472250 | 1.026312 |
2000-01-05 | 1.338454 | -1.015818 | -4.255421 | 0.463011 |
在plot( )通过对关键字的不同定义,可以画出不同的图形
- ‘bar’ or ‘barh’ for bar plots
- ‘hist’ for histogram
- ‘box’ for boxplot
- ‘kde’ or ’density’ for density plots • ‘area’ for area plots
- ‘scatter’ for scatter plots
- ‘hexbin’ for hexagonal bin plots • ‘pie’ for pie plots
条形图
plt.figure()
df.ix[5].plot(kind='bar') #ix是对行标签进行索引,其实只用这一句话就可以画出条形图,但是为了有轴线,所以用了plt
plt.axhline(0, color='k')
<matplotlib.lines.Line2D at 0x110ded668>
簇状条形图
df2 = pd.DataFrame(np.random.rand(10, 4), columns=list('ABCD')) #rand生成的是一个十行四列的matrix
df2.plot(kind='bar');
df2.head()
A | B | C | D | |
---|---|---|---|---|
0 | 0.657585 | 0.753109 | 0.239771 | 0.174211 |
1 | 0.158017 | 0.372599 | 0.913156 | 0.086046 |
2 | 0.238924 | 0.198109 | 0.149916 | 0.688851 |
3 | 0.782300 | 0.141077 | 0.724984 | 0.222786 |
4 | 0.369315 | 0.327877 | 0.215220 | 0.178366 |
堆积图(能画簇状条形图的就能画堆积图)
df2.plot(kind='bar', stacked=True)
ft = pd.read_csv('/Users/anita/Downloads/flight_delay.csv')
ft2=ft.iloc[:,-2::] [2:50]
ft2.plot(kind='bar', stacked=True)
df2 = pd.DataFrame(np.random.rand(10, 4), columns=list('ABCD')) #rand生成的是一个十行四列的matrix
ft2.plot(kind='bar');
DEP_DELAY | ARR_DELAY | |
---|---|---|
0 | -4.0 | -6.0 |
1 | 0.0 | -5.0 |
2 | -5.0 | -16.0 |
3 | -1.0 | -2.0 |
4 | -1.0 | -8.0 |
# 水平的堆积图
df2.plot(kind='barh', stacked=True)
df4 = pd.DataFrame({'a': np.random.randn(1000) + 1, 'b': np.random.randn(1000), 'c': np.random.randn(1000) - 1},columns=['a', 'b', 'c'])
plt.figure()
df4.plot(kind='hist', alpha=0.5)
df4.head()
a | b | c | |
---|---|---|---|
0 | 0.540754 | -0.700392 | -1.677638 |
1 | 2.488136 | 0.405019 | -0.362252 |
2 | 2.810745 | 0.784257 | -1.072559 |
3 | 1.632707 | -1.055843 | -0.361188 |
4 | 1.702564 | 0.272554 | -0.113543 |
直方图
df5 = pd.DataFrame({'a': np.random.randn(1000) + 1000}, columns=['a'])
plt.figure()
df5.plot(kind='hist', alpha=0.5)
# 关于random的简介,randn用于生成正态分布。。。 http://www.mamicode.com/info-detail-507676.html
plt.figure()
df['A'].diff().hist()
簇状直方图
plt.figure();
df4.plot(kind='hist', stacked=True, bins=20)
ft = pd.read_csv('/Users/anita/Downloads/flight_delay.csv')
ft.head()
##plot line graph
#ft.ARR_DELAY.plot()
#
##plot histogram
#ft.ARR_DELAY.hist()
##chnage bins
##delaybin = np.arange(-70, 2800, 10)
ft.DEP_DELAY.hist(bins=delaybin)
##flight.UNIQUE_CARRIER.value_counts().plot(kind='pie')
YEAR | FL_DATE | UNIQUE_CARRIER | AIRLINE_ID | ORIGIN_AIRPORT_ID | DEST_AIRPORT_ID | DEP_DELAY | ARR_DELAY | |
---|---|---|---|---|---|---|---|---|
0 | 2017 | 2017/1/7 | AA | 19805 | 11298 | 12889 | -4.0 | -6.0 |
1 | 2017 | 2017/1/8 | AA | 19805 | 11298 | 12889 | 0.0 | -5.0 |
2 | 2017 | 2017/1/1 | AA | 19805 | 13930 | 11298 | -5.0 | -16.0 |
3 | 2017 | 2017/1/2 | AA | 19805 | 13930 | 11298 | -1.0 | -2.0 |
4 | 2017 | 2017/1/3 | AA | 19805 | 13930 | 11298 | -1.0 | -8.0 |
一点补充:关于条形图和直方图的区别
* 条形图是用条形的长度(横置时)表示各类别频数的多少,其宽度(表示类别)则是固定的;直方图是用面积表示各组频数的多少,矩形的高度表示每一组的频数或频率,宽度则表示各组的组距,因此其高度与宽度均有意义。
* 由于分组数据具有连续性,直方图的各矩形通常是连续排列,而条形图则是分开排列。
* 条形图主要用于展示分类数据,而直方图则主要用于展示数值型数据。
累积堆积图
df4['a'].plot(kind='hist', orientation='horizontal', color='skyblue', alpha=0.5,cumulative=True)
在一个图中画出几个子图
plt.figure()
df.diff().hist(color='r', alpha=0.5, bins=50)
#因为df这个dataframe里面有四列,所以会生成四张图
散点图
df = pd.DataFrame(np.random.rand(50, 4), columns=list('ABCD'))
df.plot(kind='scatter', x='A', y='B')
#理解:dataframe里面有四个列,每个列有50个随机数
ax = df.plot(kind='scatter', x='A', y='B',color='DarkBlue', label='Group 1')
df.plot(kind='scatter', x='C', y='D',color='DarkGreen', label='Group 2', ax=ax)
三维散点图:第三维用颜色深浅表示
df.plot(kind='scatter', x='A', y='B', c='C', s=50)
三位散点图:第三维用气泡大小表示
df.C=[i*1.5 for i in df.C.values]
df.plot(kind='scatter', x='A', y='B', s=df['C']*200,alpha=0.3)
三维散点图:第三维用颜色深浅表示(六边形)
df = pd.DataFrame(np.random.randn(1000, 2), columns=['a', 'b'])
df['b'] = df[ 'b'] + np.arange(1000)
df['z'] = np.random.uniform(0, 3, 1000)
df.plot(kind='hexbin', x='a', y= 'b', C='z', reduce_C_function=np.max, gridsize=25)
饼图
series = pd.Series(np.random.rand(4), index=['a', 'b','c', 'd'], name='series')
series.plot(kind='pie', figsize=(6, 6))
#有四个色块
# 一个画布里面生成两个饼图
df = pd.DataFrame(3 * np.random.rand(4, 2), index=['a', 'b','c', 'd'], columns=['x', 'y'])
df.plot(kind='pie', subplots=True, figsize=(8, 4))
#autopct='%.2f'这个是用来生成数据标签的
series.plot(kind='pie', labels=['AA', 'BB', 'CC', 'DD'], colors=['r', 'g', 'b', 'c'], autopct='%.2f', fontsize=20, figsize=(6, 6))
课后练习 • 用调查问卷( survey_fake_info.csv ) 数据做.sum(), .mean(), .describe() • 注意不同列的结果差异 • 用调查问卷的数据做groupby • 对比不同性别等的各项差异 • 分别画出height和weight的直方图 • 画出性别、专业分布的饼图 • 画出同时以性别、专业分布的饼图 • 利用survey_fake_info.csv数据 • 写一个函数计算BMI(体重(公斤数)除以身高(米)的平方 ) • 把个人的BMI加到dataframe里作为一栏 • 然后计算survey里各人的BMI,并对比不同性别的平均BMI的差异 • 或选择BMI在正常范围之外的个体 (BMI>25或BMI
sf=pd.read_csv('/Users/anita/survey_fake_info.csv')
print(sf.head(2))
No gender Entry_year height weight isProgrammingDifficult dog_or_cat 0 1 Male 2012 171.0 70.0 No dog 1 2 Male 2012 180.0 80.0 No dog 1) 用调查问卷( survey_fake_info.csv ) 数据做.sum(), .mean(), .describe() * 注意不同列的结果差异 * 用调查问卷的数据做groupby
gb=sf.groupby('gender')
gb.mean()
No | Entry_year | height | weight | |
---|---|---|---|---|
gender | ||||
Female | 77.661972 | 2013.746479 | 162.112676 | 57.521127 |
Male | 69.864865 | 2013.662162 | 174.202703 | 68.391892 |
gb=sf.groupby('gender')
gb.describe()
• 分别画出height和weight的直方图
• 画出性别、专业分布的饼图
• 画出同时以性别、专业分布的饼图
# height直方图
sf.height.plot(kind='hist',title='height',alpha=0.5)
<matplotlib.axes._subplots.AxesSubplot at 0x11316ccc0>
# weight直方图
sf.weight.plot(kind='hist',title='weight',alpha=0.5)
# 性别分布的饼图
sf.gender.value_counts().plot(kind='pie',autopct='%.2f')
# 专业分布的饼图,title='gender',alpha=0.5
sf.isProgrammingDifficult.value_counts().sf.gender.value_counts().plot(kind='pie',autopct='%.2f',subplots=True)
new=pd.DataFrame({'x': sf.gender,'y': sf.isProgrammingDifficult,'z':sf.gender+sf.isProgrammingDifficult},columns=['x', 'y','z'])
new.sort(columns='z')
new.z.value_counts().plot(kind='pie')
x y z
0 Male No MaleNo
1 Male No MaleNo
/Users/anita/anaconda/lib/python3.5/site-packages/ipykernel/__main__.py:2: FutureWarning: sort(columns=....) is deprecated, use sort_values(by=.....)
from ipykernel import kernelapp as app
series = pd.Series([0.1] * 4, index=[’a’, ’b’, ’c’, ’d’], name=’series2’)
In [75]: series.plot(kind=’pie’, figsize=(6, 6))
series = pd.Series({'x': sf.gender},index='h')
series.value_counts.plot(kind='pie', figsize=(6, 6))stacked=True
new=pd.DataFrame({'x': sf.gender,'y': sf.isProgrammingDifficult},columns=['x', 'y'])
new.plot(kind='pie',stacked=True,subplots=True)