r - 在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")
我想要做的是通过每个点画一个箭头,然后对线下的区域和点之间的区域进行阴影处理,这意味着每个级别之间的颜色会有所不同。
预先感谢您的协助。
解决方案
这很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")
推荐阅读
- android - 无法解析 MainActivity 中的符号以及 Build Gradle 的一些问题
- .htaccess - Htaccess 减少虚假长路径
- testing - 我们可以从参数集中填充 QueryString 参数和值吗?
- php - 如何使用 PHP 获取内部数组值?
- sql - 如何组合多个选择以从多个表中获取数据
- migration - 当我在包管理器控制台中的 VS 2017 中运行更新数据库时出错
- html - 如何更改我的标题和边框块在小屏幕和大屏幕上的响应
- jquery - 如果 Object 不存在,则推送到 JSON 数组
- java - git clone 在 docker 文件中不起作用
- python - 创建另一个数据集的列之间差异的新数据集