Home > Software engineering >  Plotting a secondary x-axis in ggplot based on another column in the data
Plotting a secondary x-axis in ggplot based on another column in the data

Time:02-12

I am struggling to find if it is possible to plot a secondary x-axis (on the top of the linegraph if possible) using an entirely different column in the dataset. I've been looking for a while, so apologies if this has been answered already. For example:

Day <- c(1:10)
Revenue <- c(100,200,300,400,550,600,750,800,975,1000)
Date <- c("1/1","1/5","1/10","1/11","1/14","1/15","1/18","1/21","1/28","1/31")
a <- data.frame(Day,Revenue,Date)

I can plot "Day" on the x-axis and "Revenue" on the y-axis:

ggplot(a,(aes(Day,Revenue)))   geom_line(aes(y = Revenue))

However, is it possible to have the corresponding "Date" included at the top of the graph on a secondary x-axis that matches the primary x-axis ("Day")? Thank you in advance for any help on this!

CodePudding user response:

One option to achieve your desired result would be to make use of dup_axis and use a labeller function which assigns the value from your Date column to values of Day chosen as breaks for the primary scale:

library(ggplot2)

dup_labels <- function(x) a$Date[match(x, a$Day)]

ggplot(a,(aes(Day,Revenue)))   geom_line(aes(y = Revenue))  
  scale_x_continuous(breaks = 1:10, sec.axis = dup_axis(labels = dup_labels))

  • Related