首页 > 解决方案 > 在ggplot r中创建带有因子变量和连续变量的折线图

问题描述

我有以下数据:

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")

在此处输入图像描述

我想要做的是通过每个点画一个箭头,然后对线下的区域和点之间的区域进行阴影处理,意味着每个级别之间的颜色会有所不同。

预先感谢您的协助。

标签: rggplot2data-visualization

解决方案


这很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")

多色区域


推荐阅读