Home > Software design >  Why can't I get the X axis to be labeled?
Why can't I get the X axis to be labeled?

Time:03-04

For some reason I can't manage to get the x axis labels to show. Context: this is supposed to be continuous work over the time of a week.

library(ggplot2)
library(dplyr)

# FIGURE #####

oneseventh <- 1/7
work <-c(oneseventh)
work <- rep(work,each=7)
days_num <-c("1","2","3","4","5","6","7")
days_vec <- c(1:7)
npro_data <- data.frame(work)

npro_plot <- ggplot(npro_data, aes(x=1:7, y=work,))
npro_plot   labs(x = "Days of the Week", 
                y ="Amount of Work per day (%)", 
                title = "Non-Procrastinator",
                tag = "A",
                caption = "(based on data from ...)")   
  coord_cartesian(xlim =c(1, 7), ylim = c(0,100))  
  scale_x_discrete(labels=days_num,breaks=days_num)   
  geom_point()  
  geom_line()

#

See the plot I get with this code: See the plot I get with this code

CodePudding user response:

Since you used x = 1:7 in your ggplot(aes), you have to specify a scale_x_continuous (since 1:7 would be a continuous variable, not categorical or discrete). Also, you don't need to use the labels argument in scale_x_continuous, setting the breaks is already enough.

If it's possible, I would recommend to include all variables that are involved in the ggplot in the input dataframe (i.e. your npro_data). It'd be much easier to handle and avoid ambiguity.

library(ggplot2)

ggplot(npro_data, aes(x=1:7, y=work,))   
  labs(x = "Days of the Week", 
       y ="Amount of Work per day (%)", 
       title = "Non-Procrastinator",
       tag = "A",
       caption = "(based on data from ...)")   
  coord_cartesian(xlim =c(1, 7), ylim = c(0,100))  
  scale_x_continuous(breaks = days_vec)   
  geom_point()  
  geom_line()

geom_point

However, since in your question you mentioned that you would like the x-axis to be weekdays, then it'd probably be better to include days_num in your npro_data, and map that to the x aesthetics in ggplot. You'll need to use scale_x_discrete to change the labelling and breaks if that is the case.

  • Related