加入收藏 | 设为首页 | 会员中心 | 我要投稿 银川站长网 (https://www.0951zz.com/)- 云通信、基础存储、云上网络、机器学习、视觉智能!
当前位置: 首页 > 综合聚焦 > 编程要点 > 语言 > 正文

怎样用Python画有趋势线的散点图

发布时间:2023-09-13 12:59:23 所属栏目:语言 来源:
导读:在这篇文章中我们来了解一下“如何用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")

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

二、绘制边缘直方图

实现功能:

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画有趋势线的散点图”的内容今天就到这,感谢各位的阅读,大家可以动手实际看看,对大家加深理解更有帮助哦。

(编辑:银川站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章