核密度图可以看作是概率密度图,其纵轴可以粗略看做是数据出现的次数,与横轴围成的面积是一.
法一:seaborn的kdeplot函数专门用于画核密度估计图.
参考:https://www.jianshu.com/p/844f66d00ac1
https://yq.aliyun.com/articles/682843
import pandas as pd import numpy as np import matplotlib.pylab as plt import os import seaborn as sns ## 有时候要翻墙才能下载 # df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mpg_ggplot2.csv") # df.to_csv('../data/mpg_ggplot2.csv', index=False) df = pd.read_csv('../data/mpg_ggplot2.csv') print(df.info()) print(df.shape) # Draw Plot plt.figure(figsize=(16,10), dpi= 90) # dpi用于设置输出figure中所有字体的大小 # 将cyl列等于4的cty筛选出来做图 sns.kdeplot(df.loc[df['cyl'] == 4, "cty"], shade=True, color="g", label="Cyl=4", alpha=0.5) sns.kdeplot(df.loc[df['cyl'] == 5, "cty"], shade=True, color="deeppink", label="Cyl=5", alpha=.5) sns.kdeplot(df.loc[df['cyl'] == 6, "cty"], shade=True, color="dodgerblue", label="Cyl=6", alpha=.5) sns.kdeplot(df.loc[df['cyl'] == 8, "cty"], shade=True, color="orange", label="Cyl=8", alpha=.5) # Decoration plt.title('Density Plot of City Mileage by n_Cylinders', fontsize=22) plt.legend() plt.show()
displot()是将直方图和核密度图综合,
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
import os
import seaborn as sns
## 有时候要翻墙才能下载
# df = pd.read_csv("https://github.com/selva86/datasets/raw/master/mpg_ggplot2.csv")
# df.to_csv('../data/mpg_ggplot2.csv', index=False)
df = pd.read_csv('../data/mpg_ggplot2.csv')
# distplot图是直方图hist()和核密度图kdeplot()图的合体,
# bins参数用于调节直方图的数量
# 官网链接:http://seaborn.pydata.org/generated/seaborn.distplot.html
# 参数解释:http://www.sohu.com/a/158933070_718302
plt.figure(figsize=(16,10), dpi= 90)
sns.distplot(df.loc[df['cyl'] == 4, "cty"], color="g", label="Cyl=4", bins = 100 )
sns.distplot(df.loc[df['cyl'] == 5, "cty"], color="deeppink", label="Cyl=5", bins= 10 )
plt.legend()
plt.show()
给定一组连续值的数据,将它们分成若干小段,统计每个小段中数据的个数,并画出它们的直方图和拟合曲线.
法二:利用seaborn中的包可以快速实现,这里的拟合曲线默认不是正态曲线,而是更好的拟合了数据的分布情况,但通过参数fit可以设置拟合正态曲线.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
sns.set(style="ticks")
from sklearn import datasets
from scipy.stats import norm
iris = datasets.load_iris() # 载入鸢尾花数据集
x = iris.data[:,0] # 取narry中的第一列
sns.set_palette("hls") #设置所有图的颜色,使用hls色彩空间
# sns.distplot( x,color="r",bins=100,kde=True,)# hist=False)
# hist和kde参数默认都是True,分别用于控制是否展现直方图和拟合的曲线图
# fit可用于指定拟合正态分布,要导入from scipy.stats import norm
sns.distplot( x,bins=30, hist=True,kde_kws={'color': 'green', 'lw':3, 'label':'x'}, hist_kws={'color': 'red', 'alpha': 0.2})
plt.show()
官网教程:http://seaborn.pydata.org/generated/seaborn.distplot.html?highlight=distplot#seaborn.distplot
参考:https://www.jianshu.com/p/65395b00adbc
法三:利用round()函数保留小数点后一位或两位,再groupby作图,但效果远不如第一种.
f_train['VAR00007'] = f_train['VAR00007'].apply( lambda x: round(x, 1))
f_train = f_train.groupby(['VAR00007'])['VAR00007'].agg(['count']).reset_index()
f_train.sort_values(['VAR00007'], )
ydata = f_train['VAR00007'].tolist()
x = f_train['count'].tolist()
ydata.sort(reverse=False)
plt.scatter( ydata, x)
plt.show()