带有 pandas 分组数据的seaborn中的多个单图 [英] Multiple single plots in seaborn with pandas groupby data

查看:67
本文介绍了带有 pandas 分组数据的seaborn中的多个单图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我的问题非常具体,但我似乎找不到合适的解决方案,而且我对得到的错误输出一无所知.无论如何,我有一个从 sqlite 数据库加载的 Pandas 数据框.

My issue is very specific, i guess, but i can't seem to find a proper solution, and im clueless with the error output that i get. Anyway, i have a pandas dataframe loaded from an sqlite database.

data_frame = pd.read_sql_query(
"SELECT (total_comb + total_comb_rc) as total_comb, p_val, w_length from {tn}".format(
    tn=table_name), conn)

加载后,我按w_length"值对数据进行分组.

With that loaded, i group the data by the 'w_length' value.

for i, group in data_frame.groupby('w_length'):

现在,我想为使用 seaborn lmplot 创建的每个组绘制散点图.

Now, i want to plot a scatter plot for each group created with seaborn lmplot.

for i, group in data_frame.groupby('w_length'):
    sns.lmplot(x=group['total_comb'], y=group['p_val'],
               data=group,
               fit_reg=False)
    sns.despine()
    plt.savefig('test_scatter'+i+'.png', dpi=400)

但由于某种原因,我得到了这个输出.

But for some reason im getting, this output.

'[  6.95485628e-02   3.53641178e-01   3.46862200e+06   4.11684800e+06] not in index'

并且没有绘图文件.我知道我做错了什么,但我似乎无法弄清楚.

and no plot file. I know im doing something wrong, but i cant seem to figure it out.

pd:我知道我可以做这样的事情.

pd: i know i can do something like this.

sns.lmplot(x='total_comb', y='p_val',
       data=data_frame,
       fit_reg=False,
       hue="w_length", x_jitter=.1, col="w_length", col_wrap=3, size=4)

但我还需要每个w_length"的独立图.

but i also need the separeted plots for each 'w_length'.

谢谢!!

推荐答案

假设问题不是因为从 sql 数据库收集数据,可能是因为您调用了
sns.lmplot(x=group['total_comb'], y=group['p_val'], data=group)而不是
sns.lmplot(x='total_comb', y='p_val', data=group)

Supposing the problem is not due to the data collection from the sql database, it's probably due to the fact that you call
sns.lmplot(x=group['total_comb'], y=group['p_val'], data=group) instead of
sns.lmplot(x='total_comb', y='p_val', data=group)

这是一个工作示例,它生成两个单独的图:

Here is a working example, which produces two separate plots:

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np; np.random.seed(42)

x = np.arange(24)
y = np.random.randint(1,10, len(x))
cat = np.random.choice(["A", "B"], size=len(x))
df = pd.DataFrame({"x": x, "y": y, "cat": cat})

for i, group in df.groupby('cat'):
    sns.lmplot(x="x", y="y", data=group, fit_reg=False)
    plt.savefig(__file__+str(i)+".png")
plt.show()

这篇关于带有 pandas 分组数据的seaborn中的多个单图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆