python可视化分析绘制带趋势线的散点图和边缘直方图


Posted in Python onJune 25, 2022

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

实现功能:

在散点图上添加趋势线(线性拟合线)反映两个变量是正相关、负相关或者无相关关系。

实现代码:

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")

实现效果:

python可视化分析绘制带趋势线的散点图和边缘直方图

在散点图上添加趋势线(线性拟合线)反映两个变量是正相关、负相关或者无相关关系。红蓝两组数据分别绘制出最佳的线性拟合线。

二、绘制边缘直方图

实现功能:

python绘制边缘直方图,用于展示X和Y之间的关系、及X和Y的单变量分布情况,常用于数据探索分析。

实现代码:

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")

实现效果:

python可视化分析绘制带趋势线的散点图和边缘直方图

到此这篇关于python可视化分析绘制带趋势线的散点图和边缘直方图的文章就介绍到这了,更多相关python绘制内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
pyqt4教程之实现windows窗口小示例分享
Mar 07 Python
Windows下Eclipse+PyDev配置Python+PyQt4开发环境
May 17 Python
Python 实现一个颜色色值转换的小工具
Dec 06 Python
利用numpy+matplotlib绘图的基本操作教程
May 03 Python
详解Python函数可变参数定义及其参数传递方式
Aug 02 Python
用matplotlib画等高线图详解
Dec 14 Python
python3正则提取字符串里的中文实例
Jan 31 Python
python爬取本站电子书信息并入库的实现代码
Jan 20 Python
python opencv 检测移动物体并截图保存实例
Mar 10 Python
解决Python安装cryptography报错问题
Sep 03 Python
python 爬虫基本使用——统计杭电oj题目正确率并排序
Oct 26 Python
Python的Tqdm模块实现进度条配置
Feb 24 Python
基于Python编写一个监控CPU的应用系统
如何基于python实现单目三维重建详解
python如何读取和存储dict()与.json格式文件
Jun 25 #Python
python运行脚本文件的三种方法实例
Jun 25 #Python
如何利用python创作字符画
利用Python实时获取steam特惠游戏数据
Python first-order-model实现让照片动起来
You might like
中国广播史趣谈 — 几个历史第一次
2021/03/01 无线电
基于PHP与XML的PDF文档生成技术
2006/10/09 PHP
与文件上传有关的php配置参数总结
2013/06/14 PHP
smarty模板中使用get、post、request、cookies、session变量的方法
2014/04/24 PHP
windows7下安装php的imagick和imagemagick扩展教程
2014/07/04 PHP
解决PHP上传非标准格式的图片pjpeg失败的方法
2017/03/12 PHP
Thinkphp整合阿里云OSS图片上传实例代码
2019/04/28 PHP
javascript实现跳转菜单的具体方法
2013/07/05 Javascript
文本框倒叙输入让输入框的焦点始终在最开始的位置
2014/09/01 Javascript
Javascript单例模式的介绍和实例
2016/10/08 Javascript
浅谈AngularJS中ng-class的使用方法
2016/11/11 Javascript
探讨AngularJs中ui.route的简单应用
2016/11/16 Javascript
概述一个页面从输入URL到页面加载完的过程
2016/12/16 Javascript
Bootstrap实现提示框和弹出框效果
2017/01/11 Javascript
jQuery Ajax实现跨域请求
2017/01/21 Javascript
AngularJS页面带参跳转及参数解析操作示例
2017/06/28 Javascript
JavaScript栈和队列相关操作与实现方法详解
2018/12/07 Javascript
使用next.js开发网址缩短服务的方法
2020/06/17 Javascript
Python入门篇之编程习惯与特点
2014/10/17 Python
Python操作使用MySQL数据库的实例代码
2017/05/25 Python
Python定义二叉树及4种遍历方法实例详解
2018/07/05 Python
通过python将大量文件按修改时间分类的方法
2018/10/17 Python
Python实现二维曲线拟合的方法
2018/12/29 Python
Python时间和字符串转换操作实例分析
2019/03/16 Python
python实现抖音点赞功能
2019/04/07 Python
Python 2/3下处理cjk编码的zip文件的方法
2019/04/26 Python
基于selenium及python实现下拉选项定位select
2020/07/22 Python
CSS3制作彩色进度条样式的代码示例分享
2016/06/23 HTML / CSS
PHP中如何创建和修改数组
2012/05/02 面试题
网上签名寄语活动留言
2014/01/18 职场文书
企业人事任命书
2014/06/05 职场文书
关于环保的活动方案
2014/08/25 职场文书
工伤事故赔偿协议书
2014/10/27 职场文书
Python代码,能玩30多款童年游戏!这些有几个是你玩过的
2021/04/27 Python
python plt.plot bar 如何设置绘图尺寸大小
2021/06/01 Python
JS轻量级函数式编程实现XDM三
2022/06/16 Javascript