Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot: labeling x axis in lineplot

since a long time I despair to straighten the label of the x-axis in my plot (ggplot2). The challenge is that I have two geom_paths, each fetching the data from a different dataframe - I'm sure this will become a bit clearer in the code:

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

The goal is, to Label the X-Axis with the years from the dataframe "dx", as shown in the aes-parameter. And it works! But only if you disable the geom_paths - shown below:

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

I can't really understand why the paths destroy the labeling like this - it must be the aes parameters.

If someone has a solution for this, I would be extremely grateful!

like image 867
LePyka Avatar asked Jun 23 '26 20:06

LePyka


1 Answers

This could be achieved like so:

  1. Convert your original month variable to a date time before calling xspline. This way the interpolated date values could be easily converted back to datetime via e.g. lubridate::as_datetime.
  2. besides that you could row bind your datasets which makes plotting a bit easier
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")

enter image description here

like image 175
stefan Avatar answered Jun 26 '26 16:06

stefan