简体   繁体   中英

Seaborn Scatter Plot multiple plots with loop

I have a data set that is contains a pattern of two columns per state in the US with one of the columns defined as "cpm" and the other "spend". I am trying to determine how I can loop through each of the states and create a subplot for each state with the scatter plot with cpm as the x-axis and spend as the y-axis. While I am able to create this loop and a subplot for each state, I am not seeing data being displayed. Should I be using a different seaborn plot to achieve this?

Code:

# state list
states = [
    'alabama',
    'alaska',
    'arizona',
]

for state in states[0:3]:
    state_cpm = state + "_" + "cpm"
    state_spend = state + "_" + "spend"

    sns.pairplot(data=df, x_vars=state_cpm, y_vars=state_spend)

// df data example

alabama_cpm | alabama_spend
9.883076 | 63477.0  
10.013527   | 100110.0
10.358303   | 91535.0   

Current result:

输出

Most likely sns.scatterplot() will work. sns.pairplot will only work if you want all pairwise plots between your columns.

For example dataset is like this:

import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt

states = ['alabama','alaska','arizona']

df = pd.DataFrame(np.random.uniform(0,1,(20,6)),
                  columns = [i + "_" + j for i in states for j in ['cpm','spend']])
df.head()

alabama_cpm alabama_spend   alaska_cpm  alaska_spend    arizona_cpm arizona_spend
0   0.444585    0.305385    0.113950    0.396746    0.450246    0.072074
1   0.028701    0.446495    0.527090    0.013968    0.367590    0.598380
2   0.726407    0.214152    0.220744    0.955635    0.337088    0.128571

Then using the code you have:

fig, ax = plt.subplots(3,1,figsize=(5,5))

for i,state in enumerate(states[0:3]):
    state_cpm = state + "_" + "cpm"
    state_spend = state + "_" + "spend"

    sns.scatterplot(data=df, x=state_cpm, y=state_spend,ax=ax[i])

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM