Python绘图进行数据分析

Python绘图,防忘系列:

一、绘制带趋势线的散点图

import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings(action='once')
plt.style.use('seaborn-whitegrid')
sns.set_style("whitegrid")
print(mpl.__version__)
print(sns.__version__)
def draw_scatter(file):
    # Import Data
    df = pd.read_csv(file)
    df_select = df.loc[df.cyl.isin([4, 8]), :]

    # Plot
    gridobj = sns.lmplot(
        x="displ",
        y="hwy",
        hue="cyl",
        data=df_select,
        height=7,
        aspect=1.6,
        palette='Set1',
        scatter_kws=dict(s=60, linewidths=.7, edgecolors='black'))
    # Decorations
    sns.set(style="whitegrid", font_scale=1.5)
    gridobj.set(xlim=(0.5, 7.5), ylim=(10, 50))
    gridobj.fig.set_size_inches(10, 6)
    plt.tight_layout()
    plt.title("Scatterplot with line of best fit grouped by number of cylinders")
    plt.show()
draw_scatter("F:\数据杂坛\datasets\mpg_ggplot2.csv")

实现效果:

二、绘制边缘直方图

import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.filterwarnings(action='once')
plt.style.use('seaborn-whitegrid')
sns.set_style("whitegrid")
print(mpl.__version__)
print(sns.__version__)
def draw_Marginal_Histogram(file):
    # Import Data
    df = pd.read_csv(file)

    # Create Fig and gridspec
    fig = plt.figure(figsize=(10, 6), dpi=100)
    grid = plt.GridSpec(4, 4, hspace=0.5, wspace=0.2)
    # Define the axes
    ax_main = fig.add_subplot(grid[:-1, :-1])
    ax_right = fig.add_subplot(grid[:-1, -1], xticklabels=[], yticklabels=[])
    ax_bottom = fig.add_subplot(grid[-1, 0:-1], xticklabels=[], yticklabels=[])
    # Scatterplot on main ax
    ax_main.scatter('displ',
                    'hwy',
                    s=df.cty * 4,
                    c=df.manufacturer.astype('category').cat.codes,
                    alpha=.9,
                    data=df,
                    cmap="Set1",
                    edgecolors='gray',
                    linewidths=.5)
    # histogram on the right
    ax_bottom.hist(df.displ,
                   40,
                   histtype='stepfilled',
                   orientation='vertical',
                   color='#098154')
    ax_bottom.invert_yaxis()
    # histogram in the bottom
    ax_right.hist(df.hwy,
                  40,
                  histtype='stepfilled',
                  orientation='horizontal',
                  color='#098154')
    # Decorations
    ax_main.set(title='Scatterplot with Histograms \n displ vs hwy',
                xlabel='displ',
                ylabel='hwy')
    ax_main.title.set_fontsize(10)
    for item in ([ax_main.xaxis.label, ax_main.yaxis.label] +
                 ax_main.get_xticklabels() + ax_main.get_yticklabels()):
        item.set_fontsize(10)

    xlabels = ax_main.get_xticks().tolist()
    ax_main.set_xticklabels(xlabels)
    plt.show()
draw_Marginal_Histogram("F:\数据杂坛\datasets\mpg_ggplot2.csv")

实现效果:

三、为直方图绘制拟合曲线

3.1 定义函数

def normfun(self, x, mu, sigma):
        """
        正态分布的概率密度函数
        :param x: 数据集中的某一具体测量值
        :param mu: 数据集的平均值,反映测量值分布的集中趋势
        :param sigma: 数据集的标准差,反映测量值分布的分散程度
        :return:
        """
        pdf = np.exp(-((x - mu) ** 2) / (2 * sigma ** 2)) / (sigma * np.sqrt(2 * np.pi))
        return pdf

def draw(self, name, data):
        mean = np.mean(data)  # 计算均值
        std = np.std(data)  # 计算方差
        data1 = [(x-mean)/std for x in data]  # z-score标准化方法(数据标准化)
        num_bins = 100  # 直方图柱子的数量
        plt.figure(figsize=(20, 8))
                            # data数据  num_bins柱子个数 range取值范围[-3.3] rwidth柱子宽度
        n, bins, patches = plt.hist(data1, num_bins, range=[-5, 5], rwidth=0.8, density=0.9, facecolor='blue', alpha=0.5)
        # 直方图函数,x为x轴的值,density=1表示为概率密度,即和为一,绿色方块,色深参数0.5.返回n个概率,直方块左边线的x值,及各个方块对象
        # print(bins)
        y = self.normfun(bins, np.mean(data1), np.std(data1))  # 拟合一条最佳正态分布曲线(方程)y  代替品 ——>>> from scipy.stats import norm  y = norm.pdf(bins, mu, sigma)
        plt.plot(bins, y, 'r--')  # 绘制y的曲线
        plt.xlabel('sepal-length')  # 绘制x轴
        plt.ylabel('Probability')  # 绘制y轴
        plt.title(r'{}  $mu={}$,$sigma={}$'.format(name, mean, std))  # 标题
        plt.subplots_adjust(left=0.15)  # 左边距

        out_file = 'out_pic/%s.png' % name
        plt.savefig(out_file, transparent=True, bbox_inches='tight', dpi=200, pad_inches=0.0, set_visiable=False,
                    format='png')
        print('画图完成 %s' % out_file)
        # plt.show()

实现效果:

3.2  采用matplotlib中的mlab模块

Ref.

用Python为直方图绘制拟合正态分布曲线的两种方法 - 灰信网(软件开发博客聚合) (freesion.com)

https://www.jianshu.com/p/65395b00adbc

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
import pandas
# Load dataset
url =
"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"
names = ['sepal-length', 'sepal-width','petal-length', 'petal-width', 'class']
dataset = pandas.read_csv(url, names=names)
print(dataset.head(10))
# descriptions
print(dataset.describe())
x = dataset.iloc[:,0] #提取第一列的sepal-length变量
mu =np.mean(x) #计算均值
sigma =np.std(x)
mu,sigma
num_bins = 30 #直方图柱子的数量

n, bins, patches = plt.hist(x, num_bins,normed=1, facecolor='blue', alpha=0.5)
#直方图函数,x为x轴的值,normed=1表示为概率密度,即和为一,绿色方块,色深参数0.5.返回n个概率,直方块左边线的x值,及各个方块对象
y = mlab.normpdf(bins, mu, sigma)#拟合一条最佳正态分布曲线y 
plt.plot(bins, y, 'r--') #绘制y的曲线
plt.xlabel('sepal-length') #绘制x轴
plt.ylabel('Probability') #绘制y轴
plt.title(r'Histogram : $\mu=5.8433$,$\sigma=0.8253$')#中文标题 u'xxx' 

plt.subplots_adjust(left=0.15)#左边距 
plt.show() 

3.3 采用seaborn库中的distplot绘制

import seaborn as sns 
sns.set_palette("hls") #设置所有图的颜色,使用hls色彩空间
sns.distplot(x,color="r",bins=30,kde=True)
plt.show()
import seaborn as sns 
import matplotlib as mpl 
sns.set_palette("hls") 
mpl.rc("figure", figsize=(6,4)) 
sns.distplot(x,bins=30,kde_kws={"color":"seagreen", "lw":3 }, hist_kws={ "color": "b" }) 
plt.show()

在这里主要使用sns.distplot(增强版dist),柱子数量bins也设置为30,kde=True表示是否显示拟合曲线,如果为False则只出现直方图。
在这里注意一下它与前边mlab.normpdf方法不同的是,拟合曲线不是正态的,而是更好地拟合了数据的分布情况,如上图,因此比mlab.normpdf更为准确。
进一步设置sns.distplot,可以采用kde_kws(拟合曲线的设置)、hist_kws(直方柱子的设置),可以得到:

Ref.: https://www.jianshu.com/p/65395b00adbc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值