【问题标题】:Seaborn barplot label bars with 3rd variableSeaborn barplot 带有第三个变量的标签条
【发布时间】:2020-02-20 15:47:11
【问题描述】:

我对 Python 可视化相当陌生。我有 3 个变量的数据;月份、频率和单词。我正在尝试查看一个月内出现次数最多的单词。

import pandas as pd
import seaborn as sns

test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
             'freq':[3,5,22,6,3],
             'word':['hello','world','seaborn','seaborn','python']})


sns.barplot(x = 'month', y = 'freq', data = test)

到目前为止,我在 x 轴上有月份,在 y 轴上有频率。但是,我想用那些月份出现的单词来标记条形图。例如,“你好”应该出现在 2019 年 1 月的栏上。

【问题讨论】:

    标签: python pandas matplotlib seaborn


    【解决方案1】:

    使用plt.annotate 将标签放置在所需位置。

    hava 关键字负责正确(水平/垂直)对齐。

    test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
                 'freq':[3,5,22,6,3],
                 'word':['hello','world','seaborn','seaborn','python']})
    
    for i in test.index:
        word = test.loc[i, "word"]
        y = test.loc[i, "freq"]
        plt.annotate(word, (i, y), ha="center", va="bottom")
    
    sns.barplot(x = 'month', y = 'freq', data = test);
    

    【讨论】:

      【解决方案2】:

      如果我理解正确,你可以这样做:

      import pandas as pd
      import seaborn as sns
      
      test = pd.DataFrame({'month': ['2019-01','2019-02','2019-03','2019-04','2019-05'],
               'freq':[3,5,22,6,3],
               'word':['hello','world','seaborn','exp','python']})
      
      ax = sns.barplot(x = 'month', y = 'freq', data = test)
      
      for bar, label in zip(ax.patches, test['word']):
          x = bar.get_x()
          width = bar.get_width()
          height = bar.get_height()
          ax.text(x+width/2., height + 0.2, label, ha="center") 
      

      【讨论】:

      • 谢谢,但这不是必需的。我想要在条形顶部添加标签,因为在更大的数据集中,有些词会在几个月内重复。
      • @UmerNaeem 立即查看答案
      猜你喜欢
      • 2015-10-16
      • 2020-01-29
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-29
      • 2020-06-27
      • 2020-04-17
      相关资源
      最近更新 更多