python - 如何使线图出现在同一个图形上而不是不同的图形上?

标签 python matplotlib plot

我有一个数据框如下:

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

最佳答案

如果取消 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

关于python - 如何使线图出现在同一个图形上而不是不同的图形上?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52161219/

相关文章:

python - imshow 和 cartopy 中的图像交叉日期线问题

python - scikit-learn:cross_val_predict 仅适用于分区

python - 统计一个单词中不同字符的个数

python - OpenID 声明的标识符

python - 一个图中具有不同seaborn调色板的曲线族

matplotlib - 我可以使用 matplotlib 应用程序只分发一个额外的字体文件吗?

图中的 R 科学记数法

python - 将图像映射到球体上并绘制3D轨迹

matlab - 具有彩色组和组内不同标记的散点图

python - 如何在 Python 中创建类的不同实例?