首页 > 解决方案 > ggplot:在线条图中标记 x 轴

问题描述

很长一段时间以来,我都绝望地在我的绘图(ggplot2)中拉直 x 轴的标签。挑战在于我有两个 geom_paths,每个都从不同的数据帧中获取数据 - 我相信这在代码中会变得更加清晰:

ggplot(data=dx, aes(x = year, y=en.x ))+
  scale_y_continuous(breaks = scales::pretty_breaks(n = 2))+
  geom_path(data=ps, aes(x, y, color = "Person 1", linetype="Person 1"), size=0.5)+
  geom_path(data=pg, aes(x , y, color = "Person 2", linetype="Person 2"), size=0.5)+
  scale_color_manual("",labels = c(Nutzer1, Nutzer2), values = c("Person 1" = Nutzer1Farbe, "Person 2" = Nutzer2Farbe)) + 
  scale_linetype_manual("",labels = c(Nutzer1, Nutzer2), values=c("Person 1"=Nutzer1Format, "Person 2"=Nutzer2Format)) 

目标是用数据框“dx”中的年份标记 X 轴,如 aes 参数所示。它有效!但仅当您禁用 geom_paths - 如下所示:

ggplot(data=dx, aes(x = year, y=en.x ))+
  scale_y_continuous(breaks = scales::pretty_breaks(n = 2))+
  #geom_path(data=ps, aes(x, y, color = "Person 1", linetype="Person 1"), size=0.5)+
  #geom_path(data=pg, aes(x , y, color = "Person 2", linetype="Person 2"), size=0.5)+
  scale_color_manual("",labels = c(Nutzer1, Nutzer2), values = c("Person 1" = Nutzer1Farbe, "Person 2" = Nutzer2Farbe)) + 
  scale_linetype_manual("",labels = c(Nutzer1, Nutzer2), values=c("Person 1"=Nutzer1Format, "Person 2"=Nutzer2Format))

我真的不明白为什么路径会像这样破坏标签 - 它必须是 aes 参数。

如果有人对此有解决方案,我将非常感激!

标签: rggplot2labellinechart

解决方案


这可以像这样实现:

  1. 在调用之前将您的原始月份变量转换为日期时间xspline。这样,插值日期值可以很容易地通过例如转换回日期时间lubridate::as_datetime
  2. 除此之外,您可以对数据集进行行绑定,这使得绘图更容易
library(ggplot2)
library(tidyr)
library(dplyr)

datengesamt <- datengesamt %>% 
  # Convert to datetime
  mutate(month = as.POSIXct(month))

plot(1, 1)

ps <- xspline(datengesamt[,1], datengesamt[,2], 1, draw=FALSE)
pg <- xspline(datengesamt[,1], datengesamt[,3], 1, draw=FALSE)

pp <- list("Person 1" = data.frame(ps), "Person 2" = data.frame(pg)) %>% 
  bind_rows(.id = "id") %>% 
  mutate(x = lubridate::as_datetime(x))

ggplot(pp, aes(x, y, color = id, linetype = id)) +
  scale_y_continuous(breaks = scales::pretty_breaks(n = 2)) +
  geom_path(size=0.5) +
  scale_x_datetime(date_labels = "%Y")

在此处输入图像描述


推荐阅读