在ggplot r中创建包含因子变量和连续变量的折线图

时间:2018-10-29 12:42:34

标签: r ggplot2 data-visualization

我有以下数据:

cefr_hours <- data.frame(cefr = as.factor(c("A2", "B1", "B2", "C1", "C2")),
                         hours = c(200, 400, 600, 800, 1200))

我创建了以下情节:

  ggplot(cefr_hours, aes(x = cefr, y = hours)) +
      geom_point() +
      geom_line() +
      theme_minimal() +
      labs(title = "Hours of Guided Learning Per Level", subtitle = "Source: Cambridge English Assessment") +
      xlab("CEFR Level") +
      ylab("Number of Hours")

enter image description here

我想做的是画一个箭头穿过每个点,然后在线条下方和点之间阴影区域类似于this,这意味着每个级别之间的颜色会有所不同。

预先感谢您的协助。

1 个答案:

答案 0 :(得分:1)

这很hacky,但是可以用。我必须稍微处理一下数据,才能创建从A2到B1,然后从B1到B2的数据“组”。我相信有更好的方法可以做到这一点。

library(tidyverse)

cefr_hours <- data_frame(cefr = as.factor(c("A2", "B1", "B2", "C1", "C2")),
                         hours = c(200, 400, 600, 800, 1200))

#duplicate the data and create an indicator for group
cefr_hours <- cefr_hours %>% 
  bind_rows(cefr_hours) %>% 
  arrange(cefr) %>% 
  #create a group for A2 to B1, then B1 to B2, etc.
  mutate(group = ceiling((row_number() - 1) / 2)) %>% 
  #exclude the first and last points
  filter(group != min(group), group != max(group)) %>% 
  #convert from numeric to character
  mutate(group = letters[group])

ggplot(cefr_hours, aes(x= cefr, y=hours, group = group, fill = group)) +
  geom_ribbon(aes(ymin = 0, ymax = hours))+
  geom_point() +
  geom_line(arrow = arrow(angle = 15, ends = "last", type = "closed")) +
  theme_minimal() +
  labs(title = "Hours of Guided Learning Per Level", 
       subtitle = "Source: Cambridge English Assessment",
       x = "CEFR Level",
       y = "Number of Hours") +
  scale_fill_brewer(palette = "Dark2") + 
  theme(legend.position = "none")

Multi-colored area