来自 pandas 系列值计数的 matplotlib 条形图

matplotlib bar graph from a pandas series of value counts

我正在尝试在 python 中绘制一个图表,它会显示项目随时间的变化情况。 所以我想找出每年出现多少符合两个类别的项目,并根据这些绘制图表。

这是我在excel中的数据:

我最后想要的是一份既奇幻又动作的电影列表,以及它们每年出现的次数。 这是我得到的最终结果(正确)

即2004年有2部奇幻动作片,2005年有1部奇幻动作片等

以下是我为获得结果所采取的步骤:

#import data:
data = pd.read_csv("data.csv")

#put all fantasy movies in a list:
fantasy_movies = data[['Name', 'Genre']][(data['Genre'] == 'Fantasy')]
fantasy_movies.rename(columns={'Genre' : 'Fantasy'}, inplace = True)

#put all action movies in a list:
action_movies = data[['Name', 'Genre']][(data['Genre'] == 'Action')]
action_movies.rename(columns={'Genre' : 'Action'}, inplace = True)

#merge the two datasets:
action_fantasy = pd.merge(fantasy_movies, action_movies)

#obtain a list of unique movie names:
unique = action_fantasy.Name.unique()

#make dates the column and unique names the rows
filter_data = data[(data.Name.isin(unique))] 
table = filter_data.pivot_table(filter_data, index = ['Name'],columns=['year'])

#replace all NaNs with zero
table1 = table.fillna(0)

#Count items in years
table1.gt(0).astype(int).sum(axis=0)

现在,从这里开始,我想使用 Matplotlib 制作某种图形(我正在考虑条形图),底部会有数年,并根据 table1 结果按数量增加。 我正在努力创建一个,尽管它在技术上应该像将数据放在 x 列和将数据放在 y 列一样简单。

点赞来自 W3 Schools 的代码:https://www.w3schools.com/python/matplotlib_bars.asp

x = np.array(["A", "B", "C", "D"])
y = np.array([3, 8, 1, 10])

plt.bar(x,y)
plt.show()

我想知道我的数据格式有误吗?我的 x 轴和 y 轴是什么?

I wonder if my data is in the wrong format?

本身不是“错误”,但它在通过 pandas/matplotlib/seaborn.

绘图之前有一个 MultiIndex which is a bit of a hassle and unnecessary here. I suggest getting rid of the MultiIndex with Series.droplevel

pandas 条形图

删除 MultiIndex 后,使用 Series.plot.bar 将值绘制为 y 而索引为 x:

counts = table1.gt(0).astype(int).sum(axis=0).droplevel(0)
# year
# 2004    2
# 2005    1
# 2011    1
# 2016    1
# 2018    2
# dtype: int64

counts.plot.bar(ylabel='total')


matplotlib 条形图

如果你真的想使用 plt.bar,我建议将 Series 重置为 DataFrame,然后根据范围索引绘制总数:

counts = table1.gt(0).astype(int).sum(axis=0).droplevel(0).reset_index(name='total')
#    year  total
# 0  2004      2
# 1  2005      1
# 2  2011      1
# 3  2016      1
# 4  2018      2

plt.bar(counts.index, counts.total)
plt.xticks(ticks=counts.index, labels=counts.year)
plt.xlabel('year')
plt.ylabel('total')


seaborn 条形图

或者将 DataFrame 传递到 sns.barplot:

import seaborn as sns
sns.barplot(data=counts, x='year', y='total')