R 绘制每个日期项目的发生情况
我有这样的数据:R 绘制每个日期项目的发生情况,r,ggplot2,R,Ggplot2,我有这样的数据: dat date shop_id 1 2013-01 1 2 2013-02 2 3 2013-02 2 4 2013-02 2 5 2013-02 1 6 2013-03 3 7 2013-04 1 shop_id代表特定的店铺,year_month代表日期。如果某家店铺在特定日期上市,则表示该店铺已开业,如果不是,则表示该店铺已关闭,即2013年1月/2013-01日,1号店铺已
dat
date shop_id
1 2013-01 1
2 2013-02 2
3 2013-02 2
4 2013-02 2
5 2013-02 1
6 2013-03 3
7 2013-04 1
shop_id代表特定的店铺,year_month代表日期。如果某家店铺在特定日期上市,则表示该店铺已开业,如果不是,则表示该店铺已关闭,即2013年1月/2013-01日,1号店铺已开业,但2号和3号店铺未开业;2013年3月/2013-03日,3号店铺已开业,但1号和2号店铺未开业。由于数据是关于特定产品的销售情况,因此商店在每个日期可以出现多次。我想画出数据。
它应该看起来像下图:y轴上应该是日期,x轴上应该是店铺id,如果店铺是开放的,则填充应该是店铺id是否与特定日期一起出现
dput(dat)
structure(list(date = structure(c(1L, 2L, 2L, 2L, 2L, 3L, 4L), .Label = c("2013-01",
"2013-02", "2013-03", "2013-04"), class = "factor"), shop_id = c(1,
2, 2, 2, 1, 3, 1)), class = "data.frame", row.names = c(NA, -7L
))
这就是你要找的吗
library(tidyverse)
library(lubridate)
df %>%
group_by(shop_id) %>%
mutate(
date = ymd(paste0(date, "-01")),
start = min(date),
end = max(date) %>% ceiling_date(unit = "month") # as Julian_Hn suggested
) %>%
ungroup() %>%
ggplot(aes(x = factor(shop_id))) +
geom_linerange(aes(
ymin = start,
ymax = end
),
size = 40 # bar width
)
第二个主张:
您的日期列似乎只包含一个月,对吗?日期包括年份和月份。我想同时考虑这两个问题。我可能会在你的终值上加上一个上限日期,这样它就可以覆盖整个月,如果只有一个条目可用的话。所以end=上限\日期MaxDate,单位=月,边界上的变化=T。@PawełChabros这很好,但不完整。从数据中可以看出,1号店在2013-01年至2013-02年间以及2013-04年间开业,但在2013-03年间并未开业。因此,2013-03年和2013-04年之间的图表中肯定存在差距。我想这和最小和最大参数有关。@Banjo我添加了第二个解决方案。请检查一下。
library(tidyverse)
df %>%
group_by(date) %>%
nest() %>%
arrange(date) %>%
mutate(ypos = row_number()) %>%
unnest() %>%
ggplot() +
geom_rect(aes(
xmin = shop_id - .25,
xmax = shop_id + .25,
ymin = ypos - .5,
ymax = ypos + .5
))