Как сделать так, чтобы линейные графики отображались на одной фигуре, а не на разных? - PullRequest
0 голосов
/ 04 сентября 2018

У меня есть следующий фрейм данных:

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

Я хочу объединить столбец Age в 10 групп, а затем отобразить процент каждой группы в виде линейного графика для каждого уникального значения Contact в отдельности. Так как в Contact есть 5 уникальных значений, которые 'Email', 'SMS', 'Other', 'In Person', 'Phone', я ожидаю, что будет 1 график, на котором должно быть 5 линий, по одной для каждого из уникальных Contact значений. Но я получаю следующее:

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

1 Ответ

0 голосов
/ 04 сентября 2018

Если вы отступите plt.show(), все графики будут отображаться на одной фигуре

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...