Seaborn workaround for hue barplot

前端 未结 4 2033
时光取名叫无心
时光取名叫无心 2021-01-04 23:17

I have the following DataFrame on a Jupyter notebook which plots using seaborn a barplot:

data = {\'day_index\': [0, 1, 2, 3, 4, 5, 6],
              


        
4条回答
  •  情书的邮戳
    2021-01-04 23:45

    The hue argument probably only makes sense to introduce a new dimension to the plot, not to show another quantity on the same dimension.

    It's probably best to plot the bars without the hue argument (it's quite misleading to call it hue actually) and simply colorize the bars according to the values in the "trips" column.

    This is shown also in this question: Seaborn Barplot - Displaying Values.

    The code here would look like:

    import matplotlib.pyplot as plt
    import seaborn as sns
    import pandas as pd
    import numpy as np
    
    di = np.arange(0,7)
    avg  = np.array([708.852242,676.702190,684.572677,708.925340,781.767476,
                     1626.575057,1729.155673])
    trips = np.array([114586,120936,118882,117868,108036,43740,37508])
    df = pd.DataFrame(np.c_[di, avg, trips], columns=["day_index","avg_duration", "trips"])
    
    daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', \
    'Friday', 'Saturday', 'Sunday']
    
    plt.figure(figsize=(10,7));
    sns.set_style('ticks')
    v  = df.trips.values
    colors=plt.cm.viridis((v-v.min())/(v.max()-v.min()))
    ax = sns.barplot(data=df, x='day_index',   y='avg_duration', palette=colors)
    
    for index, row in df.iterrows():
        ax.text(row.day_index,row.avg_duration, row.trips, color='black', ha="center")
    
    ax.set_xlabel("Week Days", fontsize=16, alpha=0.8)
    ax.set_ylabel("Duration (seconds)", fontsize=16, alpha=0.8)
    ax.set_title("Week's average Trip Duration", fontsize=18)
    ax.set_xticklabels(daysOfWeek, fontsize=14)
    ax.legend(fontsize=15)
    sns.despine()
    plt.show()
    

提交回复
热议问题