Pandas:聚合列的多个条形图

2024-10-04 07:31:00 发布

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

在python pandas中,我创建了一个dataframe,其中每年有一个值,还有两个子类,即参数三元组有一个度量

import pandas, requests, numpy
import matplotlib.pyplot as plt

df

       Metric    Tag_1  Tag_2  year
0     5770832  FOOBAR1  name1  2008
1     7526436  FOOBAR1    xyz  2008
2    33972652  FOOBAR1  name1  2009
3    17491416  FOOBAR1    xyz  2009
...
16    6602920  baznar2  name1  2008
17       6608  baznar2    xyz  2008
...
30  142102944  baznar2  name1  2015
31          0  baznar2    xyz  2015

我想用x=(year,Tag_1,Tag_2)上的y值生成一个条形图,主要对years进行排序,然后对Tag_1进行排序,并根据Tag_1对条形图进行着色。有点像

^{pr2}$

我试着从一组列开始

df.plot.bar(x=['year','tag_1','tag_2']

但还没有找到一种方法,将选择分成两个相邻的酒吧组。在


Tags: importdataframepandasdf参数排序tag子类
2条回答

您也可以这样做:

fig, ax = plt.subplots()
df.groupby(['year', 'Tag_1', 'Tag_2']).sum().plot.barh(color=['r','b'], ax=ax)
fig.tight_layout()
plt.show()

PS如果不喜欢科学记数法,你可以摆脱它:

^{pr2}$

enter image description here

这会让你上路:

df = pd.read_csv('path_to_file.csv')

# Group by the desired columns
new_df = df.groupby(['year', 'Tag_1', 'Tag_2']).sum()
# Sort descending
new_df.sort('Metric', inplace=True)


# Helper function for generation sequence of 'r' 'b' colors
def get_color(i):
    if i%2 == 0:
        return 'r'
    else:
        return 'b'

colors = [get_color(j) for j in range(new_df.shape[0])]

# Make the plot
fig, ax = plt.subplots()
ind = np.arange(new_df.shape[0])
width = 0.65
a = ax.barh(ind, new_df.Metric, width, color = colors) # plot a vals
ax.set_yticks(ind + width)  # position axis ticks
ax.set_yticklabels(new_df.index.values)  # set them to the names
fig.tight_layout()
plt.show()

enter image description here

相关问题 更多 >