Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove the space between my plot and the axis in ggplot2 figures?

Tags:

plot

r

ggplot2

I am using ggplot2 to make some simple figures with a series using coordinates to make rectangles along the x-axis. However, I can't seem to figure out how to remove the padding between the actual start of the plot (x=1 location) and the leftmost edge of the plot, at what would be (0,0). For example, I am using the following code:

library(ggplot2)
library(grid)
png(filename="sample.png", width=5600, height=70)
plot.data <- data.frame(start.points=c(1),end.points=c(10))
p <- ggplot(plot.data)
p + geom_rect(aes(xmin=start.points, xmax=end.points, ymin=0, ymax=1), fill="red") + theme_bw() + ylab(paste(sprintf("%60s", ""), "\nSample_label\n")) + theme(axis.title.y = element_text(size = 30, colour = "black", angle = 0))
dev.off()

The variables my_start and my_stop are just lists of start and stop coordinates for drawing rectangles. So, this plot creates a long horizontal figure, just as I want.

The problem is, the figure looks like this:

axis_label    | <-- white space --> <-----actual plot------> <-- white space--> |

Actual plot: enter image description here

...and I want to manually control this amount of white space. I've tried setting plot.margin and panel.margin, but these seem to control other aspects of the plot. Please note, that on my sample picture the red starts at point of 1 as expected. I want this to border the y axis, and I don't want any trailing space after the end of the red bar.

Any help would be greatly appreciated! Ideally I would just remove all white space padding. Thanks!

like image 954
jake9115 Avatar asked Apr 08 '14 18:04

jake9115


1 Answers

Try to add to add scale_x_continuous(expand = c(0, 0)) to your plot code. From the help text:

expand: a numeric vector of length two, giving a multiplicative and additive constant used to expand the range of the scales so that there is a small gap between the data and the axes.

ggplot(plot.data) +
  geom_rect(aes(xmin = start.points, xmax = end.points, ymin = 0, ymax = 1), fill = "red") +
  scale_x_continuous(expand = c(0, 0))
like image 87
Henrik Avatar answered Sep 28 '22 01:09

Henrik