Plot subplots using seaborn pairplot












0














If I draw the plot using the following code, it works and I can see all the subplots in a single row. I can specifically break the number of cols into three or two and show them. But I have 30 columns and I wanted to use a loop mechanism so that they are plotted in a grid of say 4x4 sub-plots



regressionCols = ['col_a', 'col_b', 'col_c', 'col_d', 'col_e']
sns.pairplot(numerical_df, x_vars=regressionCols, y_vars='price',height=4, aspect=1, kind='scatter')
plt.show()


The code using loop is below. However, I don't see anything rendered.



 nr_rows = 4
nr_cols = 4

li_cat_cols = list(regressionCols)
fig, axs = plt.subplots(nr_rows, nr_cols, figsize=(nr_cols*4,nr_rows*4), squeeze=False)

for r in range(0, nr_rows):
for c in range(0,nr_cols):
i = r*nr_cols+c

if i < len(li_cat_cols):
sns.set(style="darkgrid")
bp=sns.pairplot(numerical_df, x_vars=li_cat_cols[i], y_vars='price',height=4, aspect=1, kind='scatter')
bp.set(xlabel=li_cat_cols[i], ylabel='Price')
plt.tight_layout()
plt.show()


Not sure what I am missing.










share|improve this question
























  • The first approach with a single call to pairplot seems desireable; unless you have a reason not to use it. I do not understand that reason. If you mind explaining it a bit more in detail, it would be easier to help. Also, having a runnable example code available helps giving answers.
    – ImportanceOfBeingErnest
    Nov 23 '18 at 13:14
















0














If I draw the plot using the following code, it works and I can see all the subplots in a single row. I can specifically break the number of cols into three or two and show them. But I have 30 columns and I wanted to use a loop mechanism so that they are plotted in a grid of say 4x4 sub-plots



regressionCols = ['col_a', 'col_b', 'col_c', 'col_d', 'col_e']
sns.pairplot(numerical_df, x_vars=regressionCols, y_vars='price',height=4, aspect=1, kind='scatter')
plt.show()


The code using loop is below. However, I don't see anything rendered.



 nr_rows = 4
nr_cols = 4

li_cat_cols = list(regressionCols)
fig, axs = plt.subplots(nr_rows, nr_cols, figsize=(nr_cols*4,nr_rows*4), squeeze=False)

for r in range(0, nr_rows):
for c in range(0,nr_cols):
i = r*nr_cols+c

if i < len(li_cat_cols):
sns.set(style="darkgrid")
bp=sns.pairplot(numerical_df, x_vars=li_cat_cols[i], y_vars='price',height=4, aspect=1, kind='scatter')
bp.set(xlabel=li_cat_cols[i], ylabel='Price')
plt.tight_layout()
plt.show()


Not sure what I am missing.










share|improve this question
























  • The first approach with a single call to pairplot seems desireable; unless you have a reason not to use it. I do not understand that reason. If you mind explaining it a bit more in detail, it would be easier to help. Also, having a runnable example code available helps giving answers.
    – ImportanceOfBeingErnest
    Nov 23 '18 at 13:14














0












0








0


1





If I draw the plot using the following code, it works and I can see all the subplots in a single row. I can specifically break the number of cols into three or two and show them. But I have 30 columns and I wanted to use a loop mechanism so that they are plotted in a grid of say 4x4 sub-plots



regressionCols = ['col_a', 'col_b', 'col_c', 'col_d', 'col_e']
sns.pairplot(numerical_df, x_vars=regressionCols, y_vars='price',height=4, aspect=1, kind='scatter')
plt.show()


The code using loop is below. However, I don't see anything rendered.



 nr_rows = 4
nr_cols = 4

li_cat_cols = list(regressionCols)
fig, axs = plt.subplots(nr_rows, nr_cols, figsize=(nr_cols*4,nr_rows*4), squeeze=False)

for r in range(0, nr_rows):
for c in range(0,nr_cols):
i = r*nr_cols+c

if i < len(li_cat_cols):
sns.set(style="darkgrid")
bp=sns.pairplot(numerical_df, x_vars=li_cat_cols[i], y_vars='price',height=4, aspect=1, kind='scatter')
bp.set(xlabel=li_cat_cols[i], ylabel='Price')
plt.tight_layout()
plt.show()


Not sure what I am missing.










share|improve this question















If I draw the plot using the following code, it works and I can see all the subplots in a single row. I can specifically break the number of cols into three or two and show them. But I have 30 columns and I wanted to use a loop mechanism so that they are plotted in a grid of say 4x4 sub-plots



regressionCols = ['col_a', 'col_b', 'col_c', 'col_d', 'col_e']
sns.pairplot(numerical_df, x_vars=regressionCols, y_vars='price',height=4, aspect=1, kind='scatter')
plt.show()


The code using loop is below. However, I don't see anything rendered.



 nr_rows = 4
nr_cols = 4

li_cat_cols = list(regressionCols)
fig, axs = plt.subplots(nr_rows, nr_cols, figsize=(nr_cols*4,nr_rows*4), squeeze=False)

for r in range(0, nr_rows):
for c in range(0,nr_cols):
i = r*nr_cols+c

if i < len(li_cat_cols):
sns.set(style="darkgrid")
bp=sns.pairplot(numerical_df, x_vars=li_cat_cols[i], y_vars='price',height=4, aspect=1, kind='scatter')
bp.set(xlabel=li_cat_cols[i], ylabel='Price')
plt.tight_layout()
plt.show()


Not sure what I am missing.







python pandas matplotlib seaborn






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 23 '18 at 11:27







Learner

















asked Nov 23 '18 at 11:10









LearnerLearner

1,3841623




1,3841623












  • The first approach with a single call to pairplot seems desireable; unless you have a reason not to use it. I do not understand that reason. If you mind explaining it a bit more in detail, it would be easier to help. Also, having a runnable example code available helps giving answers.
    – ImportanceOfBeingErnest
    Nov 23 '18 at 13:14


















  • The first approach with a single call to pairplot seems desireable; unless you have a reason not to use it. I do not understand that reason. If you mind explaining it a bit more in detail, it would be easier to help. Also, having a runnable example code available helps giving answers.
    – ImportanceOfBeingErnest
    Nov 23 '18 at 13:14
















The first approach with a single call to pairplot seems desireable; unless you have a reason not to use it. I do not understand that reason. If you mind explaining it a bit more in detail, it would be easier to help. Also, having a runnable example code available helps giving answers.
– ImportanceOfBeingErnest
Nov 23 '18 at 13:14




The first approach with a single call to pairplot seems desireable; unless you have a reason not to use it. I do not understand that reason. If you mind explaining it a bit more in detail, it would be easier to help. Also, having a runnable example code available helps giving answers.
– ImportanceOfBeingErnest
Nov 23 '18 at 13:14












1 Answer
1






active

oldest

votes


















1














I think you didnt connect each of your subplot spaces in a matrix plot to scatter plots generated in a loop.



Maybe this solution with inner pandas plots could be proper for you:
For example,



1.Lets simply define an empty pandas dataframe.



numerical_df = pd.DataFrame()


2. Create some random features and price depending on them:



numerical_df['A'] = np.random.randn(100)
numerical_df['B'] = np.random.randn(100)*10
numerical_df['C'] = np.random.randn(100)*-10
numerical_df['D'] = np.random.randn(100)*2
numerical_df['E'] = 20*(np.random.randn(100)**2)
numerical_df['F'] = np.random.randn(100)
numerical_df['price'] = 2*numerical_df['A'] +0.5*numerical_df['B'] - 9*numerical_df['C'] + numerical_df['E'] + numerical_df['D']


3. Define number of rows and columns. Create a subplots space with nr_rows and nr_cols.



nr_rows = 2 
nr_cols = 4
fig, axes = plt.subplots(nrows=nr_rows, ncols=nr_cols, figsize=(15, 8))
for idx, feature in enumerate(numerical_df.columns[:-1]):
numerical_df.plot(feature, "price", subplots=True,kind="scatter",ax=axes[idx // 4,idx % 4])


4. Enumerate each feature in dataframe and plot a scatterplot with price:



for idx, feature in enumerate(numerical_df.columns[:-1]):

numerical_df.plot(feature, "price", subplots=True,kind="scatter",ax=axes[idx // 4,idx % 4])


where axes[idx // 4, idx % 4] defines the location of each scatterplot in a matrix you create in (3.)



So, we got a matrix plot:



Scatterplot matrix






share|improve this answer























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53445599%2fplot-subplots-using-seaborn-pairplot%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    I think you didnt connect each of your subplot spaces in a matrix plot to scatter plots generated in a loop.



    Maybe this solution with inner pandas plots could be proper for you:
    For example,



    1.Lets simply define an empty pandas dataframe.



    numerical_df = pd.DataFrame()


    2. Create some random features and price depending on them:



    numerical_df['A'] = np.random.randn(100)
    numerical_df['B'] = np.random.randn(100)*10
    numerical_df['C'] = np.random.randn(100)*-10
    numerical_df['D'] = np.random.randn(100)*2
    numerical_df['E'] = 20*(np.random.randn(100)**2)
    numerical_df['F'] = np.random.randn(100)
    numerical_df['price'] = 2*numerical_df['A'] +0.5*numerical_df['B'] - 9*numerical_df['C'] + numerical_df['E'] + numerical_df['D']


    3. Define number of rows and columns. Create a subplots space with nr_rows and nr_cols.



    nr_rows = 2 
    nr_cols = 4
    fig, axes = plt.subplots(nrows=nr_rows, ncols=nr_cols, figsize=(15, 8))
    for idx, feature in enumerate(numerical_df.columns[:-1]):
    numerical_df.plot(feature, "price", subplots=True,kind="scatter",ax=axes[idx // 4,idx % 4])


    4. Enumerate each feature in dataframe and plot a scatterplot with price:



    for idx, feature in enumerate(numerical_df.columns[:-1]):

    numerical_df.plot(feature, "price", subplots=True,kind="scatter",ax=axes[idx // 4,idx % 4])


    where axes[idx // 4, idx % 4] defines the location of each scatterplot in a matrix you create in (3.)



    So, we got a matrix plot:



    Scatterplot matrix






    share|improve this answer




























      1














      I think you didnt connect each of your subplot spaces in a matrix plot to scatter plots generated in a loop.



      Maybe this solution with inner pandas plots could be proper for you:
      For example,



      1.Lets simply define an empty pandas dataframe.



      numerical_df = pd.DataFrame()


      2. Create some random features and price depending on them:



      numerical_df['A'] = np.random.randn(100)
      numerical_df['B'] = np.random.randn(100)*10
      numerical_df['C'] = np.random.randn(100)*-10
      numerical_df['D'] = np.random.randn(100)*2
      numerical_df['E'] = 20*(np.random.randn(100)**2)
      numerical_df['F'] = np.random.randn(100)
      numerical_df['price'] = 2*numerical_df['A'] +0.5*numerical_df['B'] - 9*numerical_df['C'] + numerical_df['E'] + numerical_df['D']


      3. Define number of rows and columns. Create a subplots space with nr_rows and nr_cols.



      nr_rows = 2 
      nr_cols = 4
      fig, axes = plt.subplots(nrows=nr_rows, ncols=nr_cols, figsize=(15, 8))
      for idx, feature in enumerate(numerical_df.columns[:-1]):
      numerical_df.plot(feature, "price", subplots=True,kind="scatter",ax=axes[idx // 4,idx % 4])


      4. Enumerate each feature in dataframe and plot a scatterplot with price:



      for idx, feature in enumerate(numerical_df.columns[:-1]):

      numerical_df.plot(feature, "price", subplots=True,kind="scatter",ax=axes[idx // 4,idx % 4])


      where axes[idx // 4, idx % 4] defines the location of each scatterplot in a matrix you create in (3.)



      So, we got a matrix plot:



      Scatterplot matrix






      share|improve this answer


























        1












        1








        1






        I think you didnt connect each of your subplot spaces in a matrix plot to scatter plots generated in a loop.



        Maybe this solution with inner pandas plots could be proper for you:
        For example,



        1.Lets simply define an empty pandas dataframe.



        numerical_df = pd.DataFrame()


        2. Create some random features and price depending on them:



        numerical_df['A'] = np.random.randn(100)
        numerical_df['B'] = np.random.randn(100)*10
        numerical_df['C'] = np.random.randn(100)*-10
        numerical_df['D'] = np.random.randn(100)*2
        numerical_df['E'] = 20*(np.random.randn(100)**2)
        numerical_df['F'] = np.random.randn(100)
        numerical_df['price'] = 2*numerical_df['A'] +0.5*numerical_df['B'] - 9*numerical_df['C'] + numerical_df['E'] + numerical_df['D']


        3. Define number of rows and columns. Create a subplots space with nr_rows and nr_cols.



        nr_rows = 2 
        nr_cols = 4
        fig, axes = plt.subplots(nrows=nr_rows, ncols=nr_cols, figsize=(15, 8))
        for idx, feature in enumerate(numerical_df.columns[:-1]):
        numerical_df.plot(feature, "price", subplots=True,kind="scatter",ax=axes[idx // 4,idx % 4])


        4. Enumerate each feature in dataframe and plot a scatterplot with price:



        for idx, feature in enumerate(numerical_df.columns[:-1]):

        numerical_df.plot(feature, "price", subplots=True,kind="scatter",ax=axes[idx // 4,idx % 4])


        where axes[idx // 4, idx % 4] defines the location of each scatterplot in a matrix you create in (3.)



        So, we got a matrix plot:



        Scatterplot matrix






        share|improve this answer














        I think you didnt connect each of your subplot spaces in a matrix plot to scatter plots generated in a loop.



        Maybe this solution with inner pandas plots could be proper for you:
        For example,



        1.Lets simply define an empty pandas dataframe.



        numerical_df = pd.DataFrame()


        2. Create some random features and price depending on them:



        numerical_df['A'] = np.random.randn(100)
        numerical_df['B'] = np.random.randn(100)*10
        numerical_df['C'] = np.random.randn(100)*-10
        numerical_df['D'] = np.random.randn(100)*2
        numerical_df['E'] = 20*(np.random.randn(100)**2)
        numerical_df['F'] = np.random.randn(100)
        numerical_df['price'] = 2*numerical_df['A'] +0.5*numerical_df['B'] - 9*numerical_df['C'] + numerical_df['E'] + numerical_df['D']


        3. Define number of rows and columns. Create a subplots space with nr_rows and nr_cols.



        nr_rows = 2 
        nr_cols = 4
        fig, axes = plt.subplots(nrows=nr_rows, ncols=nr_cols, figsize=(15, 8))
        for idx, feature in enumerate(numerical_df.columns[:-1]):
        numerical_df.plot(feature, "price", subplots=True,kind="scatter",ax=axes[idx // 4,idx % 4])


        4. Enumerate each feature in dataframe and plot a scatterplot with price:



        for idx, feature in enumerate(numerical_df.columns[:-1]):

        numerical_df.plot(feature, "price", subplots=True,kind="scatter",ax=axes[idx // 4,idx % 4])


        where axes[idx // 4, idx % 4] defines the location of each scatterplot in a matrix you create in (3.)



        So, we got a matrix plot:



        Scatterplot matrix







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 23 '18 at 13:02

























        answered Nov 23 '18 at 12:57









        Alexander PopkovAlexander Popkov

        262




        262






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53445599%2fplot-subplots-using-seaborn-pairplot%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            What visual should I use to simply compare current year value vs last year in Power BI desktop

            Alexandru Averescu

            Trompette piccolo