【问题标题】:How to plot a bar graph from a pandas series?如何从熊猫系列中绘制条形图?
【发布时间】:2016-09-27 15:15:06
【问题描述】:

考虑我的系列如下:第一列是article_id,第二列是频率计数。

article_id  
1         39 
2         49 
3        187 
4        159 
5        158 
        ...  
16947     14 
16948      7 
16976      2 
16977      1 
16978      1 
16980      1 

Name: article_id, dtype: int64

我使用以下命令从数据框中得到了这个系列:

logs.loc[logs['article_id'] <= 17029].groupby('article_id')['article_id'].count()

logs 是这里的数据框,article_id 是其中的列之一。

如何绘制条形图(使用 Matlplotlib),使 article_id 在 X 轴上,频率计数在 Y 轴上?

我的本​​能是使用 .tolist() 将其转换为列表,但这不会保留 article_id。

【问题讨论】:

标签: pandas matplotlib plot ipython series


【解决方案1】:

只需在 plot 的 kind 参数中使用 'bar'

示例

series = read_csv('BwsCount.csv', header=0, parse_dates=[0], index_col=0, squeeze=True, date_parser=parser)
series.plot(kind='bar')

kind 的默认值为 'line'(即 series.plot() --> 会自动绘制折线图)

供您参考:

kind : str
        ‘line’ : line plot (default)
        ‘bar’ : vertical bar plot
        ‘barh’ : horizontal bar plot
        ‘hist’ : histogram
        ‘box’ : boxplot
        ‘kde’ : Kernel Density Estimation plot
        ‘density’ : same as ‘kde’
        ‘area’ : area plot
        ‘pie’ : pie plot

【讨论】:

    【解决方案2】:

    新的pandas API 建议如下:

    import pandas as pd
    
    s = pd.Series({16976: 2, 1: 39, 2: 49, 3: 187, 4: 159, 
                   5: 158, 16947: 14, 16977: 1, 16948: 7, 16978: 1, 16980: 1},
                   name='article_id')
    
    s.plot(kind="bar", figsize=(20,10))
    

    如果您正在使用 Jupyter,则不需要 matplotlib 库。

    【讨论】:

      【解决方案3】:

      你需要IIUCSeries.plot.bar:

      #pandas 0.17.0 and above
      s.plot.bar()
      #pandas below 0.17.0
      s.plot('bar')
      

      示例:

      import pandas as pd
      import matplotlib.pyplot as plt
      
      s = pd.Series({16976: 2, 1: 39, 2: 49, 3: 187, 4: 159, 
                     5: 158, 16947: 14, 16977: 1, 16948: 7, 16978: 1, 16980: 1},
                     name='article_id')
      print (s)
      1         39
      2         49
      3        187
      4        159
      5        158
      16947     14
      16948      7
      16976      2
      16977      1
      16978      1
      16980      1
      Name: article_id, dtype: int64
      
      
      s.plot.bar()
      
      plt.show()
      

      【讨论】:

      • 谢谢。关于增加情节大小的任何建议?我在图中有 16980 个不同的值,看起来有点紧凑。我尝试使用 plt.figure(figsize=(20,10))。 PS我正在使用内联图。
      • plt.figure(figsize=(20,10)) before s.plot.bar() 非常适合我。
      • 工作。我把它放在s.plot.bar() 之后
      • @NishantKumar - 如果需要排序值 s = s.sort_values().plot.bar() 并且如果是轴 x 的索引,那么 s = s.sort_index().plot.bar()
      猜你喜欢
      • 1970-01-01
      • 2021-06-16
      • 2021-06-07
      • 1970-01-01
      • 1970-01-01
      • 2020-02-04
      • 2021-10-24
      • 2020-03-02
      相关资源
      最近更新 更多