Search code examples
rggplot2graphic

Labels along x axis disappear when using expand=c(0, 0)


I've a question regarding to the labels of the x-axis. Assume I've the following plot:

p <- ggplot(long_form_q, aes(reihe, variable)) + geom_tile(aes(fill = value), colour = "white") 

 pneu <- p + scale_fill_gradient(low = "white",high = "steelblue", limits= c(1,3), breaks=c(1,2,3)) + 
 geom_text(aes(label=long_form_textq$value)) +
 theme(axis.title.x = element_blank(),axis.title.y =element_blank())  +
 theme(axis.text.y = element_text(size=18, color = "black"), axis.text.x = element_text(size=14)) +
scale_y_discrete(labels=c(h_3x3.1="3x3", h_3x5.1="3x5", h_3x9.1 ="3x9"), expand=c(0,0)) 

of the following form:

enter image description here

How can I change the labels of the x-axis to (1,2,3,4,5,6,7,8,9,10) while using expand=c(0,0) for x ? If I'm using

scale_x_discrete(expand=c(0,0))

the labels are vanish

My dput is:

dput(long_form_q)
structure(list(reihe = c(1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 
10L, 1L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L, 1L, 2L, 3L, 4L, 
5L, 6L, 7L, 8L, 9L, 10L), variable = structure(c(1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 
2L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L), .Label = c("h_3x3.1", 
"h_3x5.1", "h_3x9.1"), class = "factor"), value = c(1, 1, 1, 
2, 1, 1, 1, 1, 1, 1, 2, 3, 2, 2, 2, 2, 2, 2, 2, 2, 3, 2, 3, 1, 
3, 3, 3, 3, 3, 3)), row.names = c(NA, -30L), .Names = c("reihe", 
"variable", "value"), class = "data.frame")

Solution

  • You're plotting continuous data along the x axis, so the correct scale is scale_x_continuous(). The reason the labels are disappearing is because you're erroneously using scale_x_discrete().

    pneu <- p + scale_fill_gradient(low = "white",high = "steelblue", limits= c(1,3), breaks=c(1,2,3)) + 
      geom_text(aes(label=value)) +
      theme(axis.title.x = element_blank(),axis.title.y =element_blank())  +
      theme(axis.text.y = element_text(size=18, color = "black"), axis.text.x = element_text(size=14)) +
      scale_y_discrete(labels=c(h_3x3.1="3x3", h_3x5.1="3x5", h_3x9.1 ="3x9"),
                       expand=c(0, 0)) + 
      scale_x_continuous(expand = c(0, 0), breaks = 1:10)
    
    pneu
    

    enter image description here

    I didn't have your variable long_form_textq$value, so I used long_form_q$value instead. Note that it is almost always a bad idea to feed data into ggplot via the aes() function. Data should be provided via the data = argument.