Kristada673
Kristada673

Reputation: 3744

How can I make line plots appear on the same figure instead of on different figures?

I have a dataframe as follows:

data = {'Contact':['Email', 'SMS', 'Email', 'Other', 'In Person', 'Other', 'SMS', 'Other', 'Phone', 'Email', 'Other', 'Phone', 
                   'Phone', 'In Person', 'Email', 'Email', 'Other', 'Other', 'Other', 'Phone', 'Other', 'Email', 'Other', 
                   'Other'],
        'Age': [34, 50, 30, 43, 38, 43, 26, 37, 30, 30, 34, 38, 48, 30, 46, 37, 29, 36, 31, 31, 53, 25, 37, 25]}

data = pd.DataFrame(data, columns=['Contact', 'Age'])
data

enter image description here

I want to bin the Age column into 10 groups, and then plot the percentage of each group as lineplot, for each unique Contact value separately. Since there are 5 unique values in Contact, which are 'Email', 'SMS', 'Other', 'In Person', 'Phone', I expect there to be 1 plot in which there should be 5 lines, one each for each of the unique Contact values. But I am getting the following:

contacts = data['Contact'].unique()

for c in contacts:
    df = data[data['Contact']==c]
    y,binEdges=np.histogram(df['Age'], bins=10)
    y = 100*y/sum(y)
    bincenters = 0.5*(binEdges[1:]+binEdges[:-1])

    plt.plot(bincenters,y,label=c)
    plt.xlabel('Age')
    plt.ylabel('Percentage count')
    plt.show()

enter image description here

Upvotes: 1

Views: 25

Answers (1)

Reblochon Masque
Reblochon Masque

Reputation: 36662

If you dedent plt.show(), all the plots will show on the same figure

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

data = {'Contact':['Email', 'SMS', 'Email', 'Other', 'In Person', 'Other', 'SMS', 'Other', 'Phone', 'Email', 'Other', 'Phone', 
                   'Phone', 'In Person', 'Email', 'Email', 'Other', 'Other', 'Other', 'Phone', 'Other', 'Email', 'Other', 
                   'Other'],
        'Age': [34, 50, 30, 43, 38, 43, 26, 37, 30, 30, 34, 38, 48, 30, 46, 37, 29, 36, 31, 31, 53, 25, 37, 25]}

data = pd.DataFrame(data, columns=['Contact', 'Age'])

contacts = data['Contact'].unique()

for c in contacts:
    df = data[data['Contact']==c]
    y,binEdges=np.histogram(df['Age'], bins=10)
    y = 100*y/sum(y)
    bincenters = 0.5*(binEdges[1:]+binEdges[:-1])

    plt.plot(bincenters,y,label=c)
    plt.xlabel('Age')
    plt.ylabel('Percentage count')
plt.show()

enter image description here

Upvotes: 2

Related Questions