r - geom_line() 用不同的线型连接特定的组变量
问题描述
geom_line() 上有很多帖子,但我没有找到特定于我需要的问题。我正在使用此处的帖子中的数据:Using `geom_line()` with X axis are factors for a simple example。但添加的是不同年份(2018 年)的更多日期。这是数据:
hist <- data.frame(date=Sys.Date() + 0:06,
counts=1:7)
hist2 <- data.frame(date=Sys.Date() - 365 + 0:06,
counts=1:7)
histdf <- rbind(hist, hist2)
histdf <- transform(histdf, weekday=factor(weekdays(date),
levels=c('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday')))
gsub("-.*","",histdf$date) -> histdf$year #because I just want the year for now
使用 dplyr 进行分组,这是一个连接每年所有点的图:
histdf %>%
group_by(year) %>%
ggplot() +
geom_line(aes(x = weekday, y = counts, color=year, group=year))
我虽然是通过不同的线类型连接每年一周中的特定日子。因此,将 M/T/W/F 与 2018 年的红色实线和 2019 年的蓝色实线连接起来。然后将 2018 年的 TH/S/S 虚线红色线和 2019 年的蓝色虚线连接起来。
非常感谢您的帮助。
解决方案
如果我正确理解了您的问题,这是一个解决方案。
我需要修改一些代码来重现您的初始数据。
library(dplyr)
library(ggplot2)
hist <- data.frame(date=Sys.Date() + 0:06,
counts=1:7)
hist2 <- data.frame(date=Sys.Date() - 365 + 0:06,
counts=1:7)
histdf <- bind_rows(hist,
hist2) %>%
mutate(weekday = lubridate::wday(date,
label = TRUE,
locale = Sys.setlocale("LC_TIME", "English"),
abbr = FALSE),
year = as.factor(lubridate::year(date)))
histdf %>%
mutate(group2 = case_when(weekday %in% c("Thursday", "Saturday", "Sunday") ~ "A",
TRUE ~ "B")) %>%
ggplot(aes(x = weekday,
y = counts,
color = year,
group = interaction(year, group2),
linetype = group2)) +
geom_line(size = 1) +
scale_linetype_manual("Linetype legend title",
values = c("A" = "dashed",
"B" = "solid"),
labels = c("A" = "TH/S/S",
"B" = "M/T/W/F")) +
scale_color_manual("Color legend title",
values = c("2018" = "red",
"2019" = "blue")) +
geom_point(size = 5, alpha = 0.5) # only for comprehension, remove it
由reprex 包(v0.3.0)于 2019 年 9 月 17 日创建
推荐阅读
- c# - 如何使用微软身份验证器应用程序批准来自我的 asp.net 核心应用程序的请求?
- webpack - [DEP_WEBPACK_SINGLE_ENTRY_PLUGIN] 和 [DEP_WEBPACK_COMPILATION_ASSETS] 警告与什么有关?
- javascript - 使用输入字段中的值作为 js 对象中的键
- python - Airflow dag 级别重试值会覆盖任务级别重试值吗?
- r - 根据行的所有单元格的值从矩阵中过滤行
- java - 如何在java中流式传输
- android - 从图库中选择图像/视频后如何获取媒体类型或 MIME 类型?
- statistics - 最佳线性回归模型的相关性与某种相关性的变量数量作为输入
- windows - 用于在文件夹中读取的 cmd 文件并将特定文件名保存为字符串
- ibm-datapower - Datapower 脚本 - 解析 JSON