如何从Pandas系列中绘制条形图?

2024-09-26 18:16:28 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑我的系列如下:第一列是ToeLoY-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),使文章\u id位于X轴上,并且Y轴上的频率计数

我的本能是使用.tolist()将其转换为列表,但这并不能保留文章的id


Tags: 数据name命令idarticle文章loc频率
3条回答

只需在绘图的实物参数中使用“bar”

示例

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

种类的默认值为“线”(即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

IIUC您需要^{}

#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()

graph

新的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

相关问题 更多 >

    热门问题