代码之家  ›  专栏  ›  技术社区  ›  EvitaSchaap

带分箱值的Seaborn折线图

  •  0
  • EvitaSchaap  · 技术社区  · 8 月前

    我有以下代码和图表:

    bins = [0, 5, 15, 25, 50, 75, 100, 125, 150, 175, 200, 250, 300, 400, 500, 600, 700, 850, 1000, 5000, 100000]
    df['articles_binned'] = pd.cut(df['ARTICLES'], bins)
    
    export_df = df.groupby(['articles_binned', 'SUB_TYPE'])['CANCELLATION_FLAG'].mean().mul(100).reset_index()
    export_df = export_df.rename(columns={'CANCELLATION_FLAG': 'Cancellation_Percentage'})
        
    # Plot the bar chart
    ax = sns.barplot(x='articles_binned', 
                y='Cancellation_Percentage', 
                hue='SUB_TYPE', 
                data=export_df)
    

    enter image description here

    但现在我实际上想在折线图中看到这些信息。每个sub_type都有不同的颜色。Seaborn不接受这些垃圾箱,即使它们是绝对的。 我该怎么办?

    1 回复  |  直到 8 月前
        1
  •  1
  •   MuhammedYunus StopTheGenocide    8 月前

    下面的示例将数据绘制为折线图,并使用颜色 SUB_TYPE .

    这个 articles_binned 列的格式为字符串。如果它不适用于您的数据,请考虑在问题中包含一些示例数据以帮助调试。

    更新 :OP确认转换 文章_装箱 列到字符串解决了这个问题。

    enter image description here

    enter image description here

        SUB_TYPE    articles_binned Cancellation_Percentage
    0   Type A  (0, 5]  14
    1   Type A  (5, 15] 21
    ...
    14  Type D  (15, 25]    14
    15  Type D  (25, 50]    13
    

    可复制示例

    import pandas as pd
    
    #
    # Data for testing
    #
    data = {
        'SUB_TYPE': [
            'Type A', 'Type A', 'Type A', 'Type A',
            'Type B', 'Type B', 'Type B', 'Type B',
            'Type C', 'Type C', 'Type C', 'Type C',
            'Type D', 'Type D', 'Type D', 'Type D'
        ],
        'articles_binned': [
            '(0, 5]', '(5, 15]', '(15, 25]', '(25, 50]',
            '(0, 5]', '(5, 15]', '(15, 25]', '(25, 50]',
            '(0, 5]', '(5, 15]', '(15, 25]', '(25, 50]',
            '(0, 5]', '(5, 15]', '(15, 25]', '(25, 50]'
        ],
        'Cancellation_Percentage': [
            14, 21, 14, 13,
            16, 25, 18, 17,
            21, 21, 19, 12,
            15, 16, 14, 13
        ]
    }
    
    df = pd.DataFrame(data)
    display(df)
    
    #
    # Plot
    #
    import seaborn as sns
    import matplotlib.pyplot as plt
    
    #Bar plot
    ax = sns.barplot(
        df, x='articles_binned', y='Cancellation_Percentage',
        hue='SUB_TYPE', legend=False
    )
    
    sns.despine(ax.figure)
    ax.figure.set_size_inches(5, 2.5)
    plt.show()
    
    #Line plot
    ax = sns.lineplot(
        df, x='articles_binned', y='Cancellation_Percentage',
        hue='SUB_TYPE',
        marker='s', linewidth=1,
    )
    ax.figure.set_size_inches(5, 3)
    sns.despine(ax.figure)
    plt.show()