Search code examples
rggplot2axis-labelsx-axis

There are more factors than what I have in the X axis being labeled


I am plotting a simple violin plot that shows violins of a variable for 2 years, so i just need the "2017" and "2018" to appear in the X axis, but more tick marks are appearing, from 2016.5, 2017.0, 2017.5... until 2018.5. In the "year" column in my data i only have the two years that i want to plot. I don't understand why is it showing like this. Here is my code and an image of the graph I am getting!

enter image description here

sum.data <- ddply(df, .(Field), summarize, mean.TF = mean(TF, na.rm = T))

(violin <- 
    ggplot(df, aes(Year, TF)) +
    geom_violin(aes(fill = factor(Year))) +
    stat_summary(fun.y=mean, geom ="point", shape=18, size=2) +
    labs(x= NULL, y= "Total FAME") +
    facet_grid(Field ~.) +
    geom_hline(data = sum.data, aes(yintercept = mean.TF), linetype = 3) +
    scale_y_continuous(breaks = seq(0,300,50)) +
    theme.custom)

Solution

  • This happened because Year is a numeric variable, and ggplot made that separation based on the values, if you had more years probably that would not happen. Here are two solutions.

    Example data

    df <-
    tibble(
      x = rep(2014:2015, each = 100),
      y = c(rnorm(100),rexp(100))
    ) 
    

    Original code

    df %>% 
      ggplot(aes(x,y))+
      geom_violin(aes(fill = factor(x)))
    

    enter image description here

    Solutions

    Transform Year in a factor/character

    That is a nice solution, because also solves the aesthetic fill, it could complicate some other geometry but that is very specific.

    df %>% 
      mutate(x = as.factor(x)) %>% 
      ggplot(aes(x,y))+
      geom_violin(aes(fill = x))
    

    Add a scale for x axis

    Using scale you can set whatever labels or breaks, but you still need to transform the variable for the aesthetic fill.

    df %>% 
      ggplot(aes(x,y))+
      geom_violin(aes(fill = factor(x)))+
      scale_x_continuous(breaks = 2014:2015)
    

    Result

    enter image description here