Home > front end >  how to decrease relative distance between geom_point() in ggplot
how to decrease relative distance between geom_point() in ggplot

Time:04-20

I have a graph that shows a lot of information and I don't want to waste space on whitespace. Is there any way to decrease the plotted distance between points on the x axis. Ideally, I want them to almost touch. I can probably do that changing absolutely every size parameter (dots, axis labels, annotations, legend entries etc) in the plot to something huge but I was wondering if there is an easier way to do so along the lines of position.dodge or so?

Here is an example saved in two different sizes to show that they still have high relative distance:

library(ggplot)

plotdata <- data.frame(my_y = rnorm(3),
                       my_x = 1:3)

pdf("yourpath/test.pdf",
    width = 4, height = 4)
ggplot(plotdata, aes(x = my_x, y = my_y))   geom_point()
dev.off()

pdf("yourpath/test2.pdf",
    width = 2, height = 2)
ggplot(plotdata, aes(x = my_x, y = my_y))   geom_point()
dev.off()

CodePudding user response:

My answer takes a similar approach to @Quinten but builds in a function for any data:

xmax<-max(plotdata$my_x);ymax=max(plotdata$my_y)
xmin<-min(plotdata$my_x);ymin=min(plotdata$my_y)

pdf("C:/temp/test.pdf",
   width = 4, height = 4)
ggplot(plotdata, aes(x = my_x, y = my_y))   geom_point() 
  xlim(xmin-0.1,xmax 0.1) 
  ylim(ymin-0.1,ymax 0.1)

dev.off()

CodePudding user response:

If I understand you correctly, you can set limits in coord_cartesian. First plot without limits:

ggplot(plotdata, aes(x = my_x, y = my_y))   geom_point()

Output:

enter image description here

With limits:

ggplot(plotdata, aes(x = my_x, y = my_y))   geom_point()   coord_cartesian(xlim=c(-1, 3),
                                                                           ylim=c(-1.5, 0.5))

Output:

enter image description here

As you can see, they are shown closer together.

  • Related