passerby51
passerby51

Reputation: 955

Extra white space on the x-axis in ggplot2

I have written this function (inspired by this Learning R post) for displaying matrices:

library(ggplot2)

tile_matrix_plot <- function(M, breaks) {

M.m <- melt(M) 
base_size <- 9
p <- ggplot(M.m, aes(Var1, Var2)) + 
  geom_tile(aes(fill=value), colour="white", size=.2) +
  scale_fill_gradient(low="blue", high="green") +
  theme_grey(base_size = base_size) +
  labs(x = "", y = "") +
  scale_x_discrete(expand=c(0,0), breaks=breaks) +
  scale_y_reverse(expand=c(0,0), breaks=breaks) +
  theme(legend.position = "none",
        axis.ticks = element_blank(),
        axis.text = element_text(size=base_size*.8, angle=90,
                                 hjust=0, colour="grey50"),
        panel.background = element_blank()) 

  return(p)
}

When I try to use it say like this

tile_matrix_plot(
 matrix(c(.7,.4,.05,.2,
          .4,.6,.05,.2,
          .05,.05,.1,.05,
          .2,.2,.05,.4), ncol=4),
 1:4)

I get extra white space at the end of the x-axis. Here is the example output Example of the image.

How can I get rid of the extra white space in the x-axis? It seems that the x-axis always extends one point beyond what I specify in scale_x_discrete using the breaks argument.

Upvotes: 3

Views: 4041

Answers (1)

eipi10
eipi10

Reputation: 93761

You can use coord_cartesian to get rid of the white space. I've also made two other changes to your function. First, the function plots matrix columns as graph rows and matrix rows as graph columns. I've changed this (by reversing Var1 and Var2 in the function) so that rows(columns) in the graph correspond to rows(columns) in the matrix. Second, I've eliminated the breaks argument to the function, since that can be set inside the function, based on the number of rows/columns in the matrix.

tile_matrix_plot <- function(M) {                         # breaks argument removed

  M.m <- melt(M) 
  base_size <- 9
  p <- ggplot(M.m, aes(Var2, Var1)) +                     # Reversed Var1 and Var2
    geom_tile(aes(fill=value), colour="white", size=.2) +
    scale_fill_gradient(low="blue", high="green") +
    theme_grey(base_size = base_size) +
    labs(x = "", y = "") +
    scale_x_discrete(expand=c(0,0), breaks=1:ncol(M)) +   # Set x-breaks here
    coord_cartesian(xlim=c(0.5, ncol(M)+0.5)) +           # To get rid of white space 
    scale_y_reverse(expand=c(0,0), breaks=1:nrow(M)) +    # Set y-breaks here
    theme(legend.position = "none",
          axis.ticks = element_blank(),
          axis.text = element_text(size=base_size*.8, angle=90,
                                   hjust=0, colour="grey50"),
          panel.background = element_blank()) 

  return(p)
}

I'm actually not sure why ggplot2 adds the extra space on the right, but coord_cartesian removes it.

Upvotes: 4

Related Questions