Plotting categorical data with pandas and matplotlib

前端 未结 5 1953
有刺的猬
有刺的猬 2020-11-28 23:27

I have a data frame with categorical data:

     colour  direction
1    red     up
2    blue    up
3    green   down
4    red     left
5    red     right
6            


        
5条回答
  •  天命终不由人
    2020-11-29 00:19

    You could also use countplot from seaborn. This package builds on pandas to create a high level plotting interface. It gives you good styling and correct axis labels for free.

    import pandas as pd
    import seaborn as sns
    sns.set()
    
    df = pd.DataFrame({'colour': ['red', 'blue', 'green', 'red', 'red', 'yellow', 'blue'],
                       'direction': ['up', 'up', 'down', 'left', 'right', 'down', 'down']})
    sns.countplot(df['colour'], color='gray')
    

    It also supports coloring the bars in the right color with a little trick

    sns.countplot(df['colour'],
                  palette={color: color for color in df['colour'].unique()})
    

提交回复
热议问题