如何在Python中针对日期列绘制分类变量 [英] How to plot categorical variable against a date column in Python

查看:53
本文介绍了如何在Python中针对日期列绘制分类变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的数据看起来像这样

Date         Fruit
2017-01-01   Orange
2017-01-01   Apple
2017-01-08   Orange
2017-01-09   Orange
2017-01-09   Apple

我想在单个绘图中绘制橘子数,按日期划分的苹果数.我该怎么办?

I want to plot Number of Oranges, Number of Apples by Date in a single plot. How would I do that?

我按日期将它们分组,然后看到结果.

I grouped them by Date and I see the result.

df.groupby(['Date','Fruit']).size()

Date         Fruit
2017-01-01   Orange  1
             Apple   1
2017-01-08   Orange  1
2017-01-09   Orange  1
             Apple   1

我尝试过此方法,但是它给出了具有两个类别的条形图,但没有针对日期的条形图.

I tried this but it gives a bar plot having two categories but not against the dates.

sns.catplot(x="Fruit", hue="Fruit", kind="count",
            palette="pastel", edgecolor=".6",
            data=df);

如何绘制在x轴上具有日期,每个日期的苹果数量和橘子数量的图形?

How can plot a graph have Date on the x-axis and number of apples and the number of oranges for each date?

推荐答案

对数据集进行构架:

df = pd.DataFrame(columns=["Date", "Fruit"], data=[['2017-01-01','Orange'], ['2017-01-01','Orange'], ['2017-01-01','Apple'], ['2017-01-08','Orange'], ['2017-01-09','Orange'], ['2017-01-09','Apple']])

通过使用unstack和按条形图分组可以绘制:

By using unstack and group by a bar plot can be drawn:

(df
 .groupby(['Date', 'Fruit'])
 .size()
 .unstack()
 .plot.bar()
)

这篇关于如何在Python中针对日期列绘制分类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆