首页 > 解决方案 > 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 年的蓝色虚线连接起来。

非常感谢您的帮助。

标签: rggplot2

解决方案


如果我正确理解了您的问题,这是一个解决方案。
我需要修改一些代码来重现您的初始数据。

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 日创建


推荐阅读