Python数据分析--Pandas知识点(三)

本文主要是总结学习pandas过程中用到的函数和方法, 在此记录, 防止遗忘.

Python数据分析--Pandas知识点(一)

Python数据分析--Pandas知识点(二)

下面将是在知识点一, 二的基础上继续总结.

前面所介绍的都是以表格的形式中展现数据, 下面将介绍Pandas与Matplotlib配合绘制出折线图, 散点图, 饼图, 柱形图, 直方图等五大基本图形.

Matplotlib是python中的一个2D图形库, 它能以各种硬拷贝的格式和跨平台的交互式环境生成高质量的图形, 比如说柱状图, 功率谱, 条形图, 误差图, 散点图等. 其中, matplotlib.pyplot 提供了一个类似matlab的绘图框架, 使用该框架前, 必须先导入它.

19. 折线图

折线图: 数据随着时间的变化情况描点连线而形成的图形, 通常被用于显示在相等时间间隔下数据的趋势. 下面将采用两种方式进行绘制折线图, 一种是pandas中plot()方法, 该方法用来绘制图形, 然后在matplotlib中的绘图框架中展示; 另一种则是直接利用matplotlib中绘图框架的plot()方法.

19.1 采用pandas中的plot()方法绘制折线图

在pandas中绘制折线图的函数是plot(x=None, y=None, kind='line', figsize = None, legend=Truestyle=None, color = "b", alpha = None):

第一个: x轴的数据

第二个: y轴的数据

第三个: kind表示图形种类, 默认为折线图

第四个: figsize表示图像大小的元组

第五个: legend=True表示使用图例, 否则不使用, 默认为True.

第六个: style表示线条样式

第七个: color表示线条颜色, 默认为蓝色

第八个: alpha表示透明度, 介于0~1之间.

plot()函数更多参数请查看官方文档:http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.plot.html?highlight=plot#pandas.DataFrame.plot

数据来源: https://assets.datacamp.com/production/course_1639/datasets/percent-bachelors-degrees-women-usa.csv

 import pandas as pd
import matplotlib.pyplot as plt
#第一步读取数据: 使用read_csv()函数读取csv文件中的数据
df = pd.read_csv(r"D:\Data\percent-bachelors-degrees-women-usa.csv")
#第二步利用pandas的plot方法绘制折线图
df.plot(x = "Year", y = "Agriculture")
#第三步: 通过plt的show()方法展示所绘制图形
plt.show()

在执行上述代码过程了报错ImportError: matplotlib is required for plotting, 若遇到请点击参考办法

最终显示效果:

Python数据分析--Pandas知识点(三)

如果想将实线变为虚线呢, 可修改style参数为"--":

 import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r"D:\Data\percent-bachelors-degrees-women-usa.csv")
#添加指定的style参数
df.plot(x = "Year", y = "Agriculture", style = "--")
plt.show()

Python数据分析--Pandas知识点(三)

添加坐标轴标签以及标题:

 import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r"D:\Data\percent-bachelors-degrees-women-usa.csv")
df.plot(x = "Year", y = "Agriculture", style = "--")
#添加横坐标轴标签
plt.xlabel("Year")
#添加纵坐标轴标签
plt.ylabel("Percent")
#添加标题
plt.title("Percent of American women earn Agriculture's degree")
plt.show()

Python数据分析--Pandas知识点(三)

19.2 采用matplotlib.pyplot的plot()方法绘制折线图

matplotlib.pyplot.plot(x, y, style, color, linewidth)函数的参数分别表示: x轴数据, y轴数据, style线条样式, color线条颜色, linewidth线宽.

 import pandas as pd
import matplotlib.pyplot as plt
#第一步: 读取数据
df = pd.read_csv(r"D:\Data\percent-bachelors-degrees-women-usa.csv")
#第二步: 将所需数据赋值给对应的变量
df_year, df_Agriculture = df["Year"], df["Agriculture"]
#第三步: 用matplotlib中绘图框架的plot()方法绘制红色的折线图
plt.plot(df_year, df_Agriculture,"-", color = "r",linewidth = 10)
#添加横坐标轴标签
plt.xlabel("Year")
#添加纵坐标轴标签
plt.ylabel("Percent")
#添加标题
plt.title("Percent of American women earn Agriculture's degree")
plt.show()

显示效果:

Python数据分析--Pandas知识点(三)

20. 散点图

散点图: 用两组数据构成多个坐标点, 考察坐标点的分布, 判断两变量之间是否存在某种关联或总结坐标点的分布模式. 各点的值由点在坐标中的位置表示, 用不同的标记方式表示各点所代表的不同类别.

20.1 采用pandas中的plot()方法绘制散点图

只需将plot()函数中的kind参数的值改为"scatter"即可.

数据来源: http://archive.ics.uci.edu/ml/machine-learning-databases/iris/

 import pandas as pd
import matplotlib.pyplot as plt
#读取数据
df = pd.read_csv(r"D:\Data\Iris.csv")
#原始数据中没有给出字段名, 在这里指定
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
#指定x轴与y轴数据并绘制散点图
df.plot(x = "sepal_len", y = "sepal_wid", kind = "scatter" )
#添加横坐标轴标签
plt.xlabel("sepal length")
#添加纵坐标轴标签
plt.ylabel("sepal width")
#添加标题
plt.title("Iris sepal length and width analysis")
plt.show()

Python数据分析--Pandas知识点(三)

20.2 采用matplotlib.pyplot的plot()方法绘制散点图

 import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r"D:\Data\Iris.csv")
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
#用绘图框架的plot()方法绘图, 样式为".", 颜色为红色
plt.plot(df["sepal_len"], df["sepal_wid"],".", color = "r")
plt.xlabel("sepal length")
plt.ylabel("sepal width")
plt.title("Iris sepal length and width analysis")
plt.show()

Python数据分析--Pandas知识点(三)

21. 饼图

饼图: 将一个圆形划分为多个扇形的统计图, 它通常被用来显示各个组成部分所占比例.

由于在绘制饼状图先要对数据进行分类汇总, 先查看数据的总体信息

 import pandas as pd
df = pd.read_csv(r"D:\Data\Iris.csv")
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
#查看数据总体信息
df.describe()

Python数据分析--Pandas知识点(三)

可以看出每一列都是149个数据, 那么接下来对species列进行分类汇总

 import pandas as pd
df = pd.read_csv(r"D:\Data\Iris.csv")
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
#对species列进行分类并对sepal_len列进行计数
df_gbsp = df.groupby("species")["sepal_len"].agg(["count"])
df_gbsp

Python数据分析--Pandas知识点(三)

21.1 采用pandas中的plot()方法绘制饼状图

 import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r"D:\Data\Iris.csv")
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
#对species列进行分类并对sepal_len列进行计数
df_gbsp = df.groupby("species")["sepal_len"].agg(["count"])
#绘制图形样式为饼图, 百分比保留两位小数, 字体大小为20, 图片大小为6x6, subplots为True表示将数据每列绘制为一个子图,legend为True表示隐藏图例
df_gbsp.plot(kind = "pie", autopct='%.2f%%', fontsize=20, figsize=(6, 6), subplots = True, legend = False)
plt.show()

Python数据分析--Pandas知识点(三)

21.2 采用matplotlib.pyplot的pie()方法绘制饼状图

pie(x, explode = None, labels = None, colors=None, autopct=None)的参数分别表示:

第一个: x表示要绘图的序列

第二个: explode要突出显示的组成部分

第三个: labels各组成部分的标签

第四个: colors各组成部分的颜色

第五个: autopct数值显示格式

 import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r"D:\Data\Iris.csv")
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
df["species"] = df["species"].apply(lambda x: x.replace("Iris-",""))
df_gbsp = df.groupby("species",as_index = False)["sepal_len"].agg({"counts": "count"})
#对counts列的数据绘制饼状图.
plt.pie(df_gbsp["counts"],labels = df_gbsp["species"], autopct = "%.2f%%" )
plt.show()

Python数据分析--Pandas知识点(三)

22. 柱形图

柱形图: 又称为长条图, 是一种以长方形的长度为变量的统计图. 柱形图常用来比较两个或以上的数据不同时间或者不同条件).

22.1 采用pandas的plot()方法绘制柱形图

 import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r"D:\Data\Iris.csv")
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
df["species"] = df["species"].apply(lambda x: x.replace("Iris-",""))
#对species分组求均值
df_gbsp = df.groupby("species", as_index = False).mean()
#绘制柱形图
df_gbsp.plot(kind = "bar")
#修改横坐标轴刻度值
plt.xticks(df_gbsp.index,df_gbsp["species"],rotation=360)
plt.show()

Python数据分析--Pandas知识点(三)

当然也可以绘制横向柱形图

 import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r"D:\Data\Iris.csv")
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
df["species"] = df["species"].apply(lambda x: x.replace("Iris-",""))
df_gbsp = df.groupby("species", as_index = False).mean()
#将bar改为barh即可绘制横向柱形图
df_gbsp.plot(kind = "barh")
plt.yticks(df_gbsp.index,df_gbsp["species"],rotation=360)
plt.show()

Python数据分析--Pandas知识点(三)

若想要将样式改为堆积柱形图:

#修改stacked参数为True即可
df_gbsp.plot(kind = "barh", stacked = True)

Python数据分析--Pandas知识点(三)

22.2 采用matplotlib.pyplot的bar()方法绘制柱形图

bar( x, height, width=0.8, color = None, label =None, bottom =None, tick_label = None)的参数分别表示:

第一个: x表示x轴的位置序列

第二个: height表示某个系列柱形图的高度

第三个: width表示某个系列柱形图的宽度

第四个: label表示图例

第五个: bottom表示底部为哪个系列, 常被用在堆积柱形图中

第六个: tick_label刻度标签

 import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r"D:\Data\Iris.csv")
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
df["species"] = df["species"].apply(lambda x: x.replace("Iris-",""))
df_gbsp = df.groupby("species").mean()
#绘制"sepal_len"列柱形图
plt.bar(df_gbsp.index,df_gbsp["sepal_len"], width= 0.5 , color = "g")
plt.show()

Python数据分析--Pandas知识点(三)

绘制多组柱形图:

 import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r"D:\Data\Iris.csv")
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
df["species"] = df["species"].apply(lambda x: x.replace("Iris-",""))
df_gbsp = df.groupby("species").mean()
#计算有多少个列
len_spe = len(df_gbsp.count())
#计算有多少行, 并生成一个步进为1的数组
index = np.arange(len(df_gbsp.index))
#设置每组总宽度
total_width= 1.4
#求出每组每列宽度
width = total_width/len_spe
#对每个字段进行遍历
for i in range(len_spe):
#得出每个字段的名称
het = df_gbsp.columns[i]
#求出每个字段所包含的数组, 也就是对应的高度
y_values = df_gbsp[het]
#设置x轴标签
x_tables = index * 1.5 + i*width
#绘制柱形图
plt.bar(x_tables, y_values, width =width)
#通过zip接收(x_tables,y_values),返回一个可迭代对象, 每一个元素都是由(x_tables,y_values)组成的元组.
for x, y in zip(x_tables, y_values):
#通过text()方法设置数据标签, 位于柱形中心, 最顶部, 字体大小为10.5
plt.text(x, y ,'%.2f'% y ,ha='center', va='bottom', fontsize=10.5)
#设置x轴刻度标签位置
index1 = index * 1.5 + 1/2
#通过xticks设置x轴标签为df_gbsp的索引
plt.xticks(index1 , df_gbsp.index)
#添加图例
plt.legend(df_gbsp.columns)
plt.show()

Python数据分析--Pandas知识点(三)

绘制堆积柱形图

 import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r"D:\Data\Iris.csv")
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
df["species"] = df["species"].apply(lambda x: x.replace("Iris-",""))
df_gbsp = df.groupby("species").mean()
len_spe = len(df_gbsp.count())
index = np.arange(len(df_gbsp.index))
total_width= 1
width = total_width/len_spe
ysum = 0
for i in range(len_spe):
het = df_gbsp.columns[i]
y_values = df_gbsp[het]
#将x轴标签改为index/2, 之后在设置bottom为ysum.
plt.bar(index/2, y_values, width =width, bottom = ysum)
ysum, ysum1= ysum+ y_values, ysum
#计算堆积后每个区域中心对应的高度
zsum = ysum1 + (ysum - ysum1)/2
for x, y , z in zip(index/2, y_values, zsum):
plt.text(x, z ,'%.2f'% y ,ha='center', va='center', fontsize=10.5)
plt.xticks(index/2 , df_gbsp.index)
plt.legend(df_gbsp.columns)
plt.show()

Python数据分析--Pandas知识点(三)

bar()函数是用来绘制竖直柱形图, 而绘制横向柱形图用barh()函数即可, 两者用法相差不多

23. 直方图

直方图: 由一系列高度不等的长方形表示数据分布的情况, 宽度表示间隔, 高度表示在对应宽度下出现的频数.

23.1 采用pandas中的plot()方法绘制折线图

将plot()方法中的kind参数改为"hist"即可, 参考官方文档: http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html#histograms

 import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r"D:\Data\Iris.csv")
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
df["species"] = df["species"].apply(lambda x: x.replace("Iris-",""))
df_gbsp = df["sepal_len"]
#绘制直方图
df_gbsp.plot(kind = "hist")
plt.show()

Python数据分析--Pandas知识点(三)

#可修改cumulative=True实现累加直方图, 以及通过bins参数修改分组数
df_gbsp.plot(kind = "hist", cumulative='True', bins = 20)

Python数据分析--Pandas知识点(三)

23.2 采用matplotlib.pyplot的hist()方法绘制折线图

 import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv(r"D:\Data\Iris.csv")
df.columns = ['sepal_len', 'sepal_wid', 'petal_len', 'petal_wid','species']
df["species"] = df["species"].apply(lambda x: x.replace("Iris-",""))
#hist()方法绘制直方图
plt.hist(df["sepal_wid"], bins =20, color = "k")
plt.show()

Python数据分析--Pandas知识点(三)

#修改为累加直方图, 透明度为0.7
plt.hist(df["sepal_wid"], bins =20, color = "K", cumulative=True, alpha = 0.7)

Python数据分析--Pandas知识点(三)

以上是对pandas的几个基本可视化视图的总结, 更多pandas可视化相关参考官方文档: http://pandas.pydata.org/pandas-docs/version/0.15.0/visualization.html

参考资料:

https://www.cnblogs.com/dev-liu/p/pandas_plt_basic.html

https://blog.csdn.net/qq_29721419/article/details/71638912

上一篇:vs提示“当前不会命中断点,源代码与原始版本不同”的一种解决办法


下一篇:Linux系统产生随机数/dev/random 和 /dev/urandom