【可视化1】利用matplotlib.pylot画图

本文详细介绍了使用matplotlib.pyplot进行数据可视化的方法,包括画图基础、设置坐标区间、线条样式、散点图、折线图、添加注释、颜色设置、图例配置、直方图以及多子图的绘制。还提到了条形图、簇状条形图、堆积图和直方图的使用,强调了条形图和直方图的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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]
ABCD
2000-01-010.459922-1.1070271.1348670.166950
2000-01-022.346380-2.2311071.8811841.231315
2000-01-033.395658-0.939746-2.1784300.909716
2000-01-043.153648-1.494069-2.4722501.026312
2000-01-051.338454-1.015818-4.2554210.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()
.dataframe thead tr:only-child th { text-align: right; } .dataframe thead th { text-align: left; } .dataframe tbody tr th { vertical-align: top; }
ABCD
00.6575850.7531090.2397710.174211
10.1580170.3725990.9131560.086046
20.2389240.1981090.1499160.688851
30.7823000.1410770.7249840.222786
40.3693150.3278770.2152200.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_DELAYARR_DELAY
0-4.0-6.0
10.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()
abc
00.540754-0.700392-1.677638
12.4881360.405019-0.362252
22.8107450.784257-1.072559
31.632707-1.055843-0.361188
41.7025640.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')
YEARFL_DATEUNIQUE_CARRIERAIRLINE_IDORIGIN_AIRPORT_IDDEST_AIRPORT_IDDEP_DELAYARR_DELAY
020172017/1/7AA198051129812889-4.0-6.0
120172017/1/8AA1980511298128890.0-5.0
220172017/1/1AA198051393011298-5.0-16.0
320172017/1/2AA198051393011298-1.0-2.0
420172017/1/3AA198051393011298-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()
NoEntry_yearheightweight
gender
Female77.6619722013.746479162.11267657.521127
Male69.8648652013.662162174.20270368.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)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值