【问题标题】:Plotting categorical data with pandas and matplotlib使用 pandas 和 matplotlib 绘制分类数据
【发布时间】:2015-09-10 19:59:24
【问题描述】:

我有一个包含分类数据的数据框:

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

我想根据类别生成一些图表,例如饼图和直方图。是否可以不创建虚拟数字变量?类似的东西

df.plot(kind='hist')

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以在系列中简单地使用value_counts

    df['colour'].value_counts().plot(kind='bar')
    

    【讨论】:

    • 建议将df["colour"].value_counts().plot(kind='bar') 作为常用替代方案
    • 可以指定x标签的顺序吗?
    • 是的,您可以明确指定 x-labels 的顺序,例如df['colour'].value_counts()[['green', 'yellow', 'blue', 'red']]
    • 你能告诉我如何调整这个情节吗?我的意思是,如果我想为每个班级更改颜色,或者我想为其添加一个图例。
    • 这些天来,df["colour"].value_counts().plot().bar() 的语法更流行——但这为我省去了一些痛苦!谢谢!
    【解决方案2】:

    您可能会从 statsmodels 中找到有用的 mosaic 图。这也可以对差异进行统计突出显示。

    from statsmodels.graphics.mosaicplot import mosaic
    plt.rcParams['font.size'] = 16.0
    mosaic(df, ['direction', 'colour']);
    

    但要注意 0 大小的单元格 - 它们会导致标签出现问题。

    详情请见this answer

    【讨论】:

    • 谢谢。我不断收到 ValueError: Cannot convert NA to integer on it.
    • 这就是我引用this answer的原因。它应该有助于解决这个问题。
    【解决方案3】:

    像这样:

    df.groupby('colour').size().plot(kind='bar')
    

    【讨论】:

      【解决方案4】:

      您也可以使用seaborn 中的countplot。该软件包基于pandas 创建高级绘图界面。它免费为您提供良好的样式和正确的轴标签。

      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')
      

      它还支持用一个小技巧为条形上色

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

      【讨论】:

      • 嗨。如何修改变量的名称,例如,我有近 10 个变量类别,当我制作此图时,名称相互重叠。我能做些什么来避免这种情况发生?我应该增加 figsize 还是什么?
      【解决方案5】:

      要在同一个图上将多个分类特征绘制为条形图,我建议:

      import pandas as pd
      import matplotlib.pyplot as plt
      
      df = pd.DataFrame(
          {
              "colour": ["red", "blue", "green", "red", "red", "yellow", "blue"],
              "direction": ["up", "up", "down", "left", "right", "down", "down"],
          }
      )
      
      categorical_features = ["colour", "direction"]
      fig, ax = plt.subplots(1, len(categorical_features))
      for i, categorical_feature in enumerate(df[categorical_features]):
          df[categorical_feature].value_counts().plot("bar", ax=ax[i]).set_title(categorical_feature)
      fig.show()
      

      【讨论】:

        【解决方案6】:

        您可以简单地使用value_counts 并将sort 选项设置为False。这将保留类别的顺序

        df['colour'].value_counts(sort=False).plot.bar(rot=0)
        

        【讨论】:

          【解决方案7】:

          使用情节

          import plotly.express as px
          px.bar(df["colour"].value_counts())
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-06-28
            • 2019-08-14
            • 2020-06-20
            • 1970-01-01
            • 1970-01-01
            • 2016-06-04
            • 2017-07-11
            相关资源
            最近更新 更多