在ggplot中绘制2个以上的因子变量

时间:2018-04-16 08:32:48

标签: r ggplot2

我的数据集如下所示,

dat <- data.frame(ID = c(150,151,155,155,155,155,150), year = c(1995,2011,2012,2012,2013,2012,2013), Acceptance = c(no,yes,yes,yes,yes,no,no));

我想绘制条形图,ID为155,年份为X轴,var 3仅显示是。

我尝试过以下代码

cl_d <- dat %>%
  filter(ID==155)%>%
  filter(year(Date)>2000)%>%
  group_by(ID, year)%>%
  summarise(count=n())

ggplot(cl_d, aes(year, count))+
  geom_bar(stat='identity')

条形图应显示&#34;是&#34;的接受次数。特定ID 155的日期大于2000

4 个答案:

答案 0 :(得分:1)

嘿,这段代码应该可以工作我总是尽量避免使用插件,如果你有任何疑问,只需要问一下!

dat <- data.frame(c(150,151,155,155,155,155,150), 
c(1995,2011,2012,2012,2013,2012,2013), 
c("no","yes","yes","yes","yes","no","no"))
colnames(dat)[1] <- "ID"
colnames(dat)[2] <- "Date"
colnames(dat)[3] <- "claim_count1"
NewData <- dat[dat$ID==155 & dat$Date > 2000 & dat$claim_count1== "yes",]
ggplot(data=NewData, aes(x=Date)) + geom_bar(stat ="count")

答案 1 :(得分:1)

此?

dat %>%
  filter(ID==155)%>%
  filter(Acceptance == "yes") %>% 
  filter(year>2000) %>% 
  group_by(year) %>% 
  count() %>% 
 ggplot(aes(year, n))+
   geom_col()

enter image description here

答案 2 :(得分:1)

这是你之后的事吗?

library(tidyverse);
dat %>%
    filter(ID == 155 & year >= 2000 & Acceptance == "yes") %>%
    count(ID, year) %>%
    ggplot(aes(as.factor(year), n)) +
    geom_bar(stat = "identity") +
    labs(x = "Year", y = "Count")

enter image description here

样本数据

dat <- data.frame(
    ID = c(150,151,155,155,155,155,150),
    year = c(1995,2011,2012,2012,2013,2012,2013),
    Acceptance = c("no","yes","yes","yes","yes","no","no"));

答案 3 :(得分:1)

您似乎希望year采用日期格式,图表也采用日期格式。如果是这种情况,请参阅以下代码:

dat <- data.frame(ID = c(150,151,155,155,155,155,150), 
 year =  c(1995,2011,2012,2012,2013,2012,2013), 
 Acceptance = c("no","yes","yes","yes","yes","no","no"))

dat$year <- as.Date(ISOdate(dat$year, 1, 1))

cl_d <- dat %>% filter(ID==155) %>%
  subset(year > as.Date("2000-01-01")) %>%
         group_by(ID, year) %>%
         summarise(count=n())

ggplot(cl_d, aes(year, count)) + 
  geom_bar(stat='identity') + 
  scale_x_date(date_labels ="%Y", date_breaks = "1 year")