0

I am trying to produce a normal distribution with vertical lines going down from the x-axis below the graph.

So far I have been able to draw the distribution curve and add lines that go above the x-axis (figure 1) and combine two plots where the lines are below (figure 2).

The problem with figure 1 is that they cover the graph instead of appearing below, and in figure 2 nothing is aligned. Can someone help me with this? I don't mind what method/how hacky the solution is as long as it looks ok.

Figure 1

Figure 1

Figure 2

Figure 2

Code:

library(gridExtra)
library(ggplot2)

# plot 1
p1 <- ggplot(data.frame(x = c(-3, 3)), aes(x)) +
  stat_function(fun = dnorm, 
            fill = "mediumpurple",
            alpha = 0.4,
            xlim = c(-1.96,1.96),
            geom = "area") +
  stat_function(fun = dnorm) +
  xlab(expression(mu)) +
  ylab("") +
  theme_classic() +
  theme(axis.title.x = element_text(vjust=22, size = 25),
        axis.text.x =  element_text(size = 13),
        axis.text.y =  element_text(size = 13))
 
 plot(p1)

 # plot 2
 p2 <- ggplot() +
   geom_vline(xintercept =-1.96, linetype=2) +
   geom_vline(xintercept = 1.96, linetype=2) +
   geom_vline(xintercept = 0, size = 1.1) +
   xlim(-3, 3) +
   xlab("") +
   theme_classic() +
   theme(axis.line.x = element_blank(),
         axis.ticks.x = element_blank(),
         axis.text.x = element_blank())

 grid.arrange(p1, p2, nrow=2)
Community
  • 1
  • 1
morgan121
  • 2,213
  • 1
  • 15
  • 33

1 Answers1

0

You can align the two graphs using this (as per Left align two graph edges (ggplot)):

gA <- ggplotGrob(p1)
gB <- ggplotGrob(p2)
maxWidth = grid::unit.pmax(gA$widths[2:5], gB$widths[2:5])
gA$widths[2:5] <- as.list(maxWidth)
gB$widths[2:5] <- as.list(maxWidth)  
grid.arrange(gA, gB, ncol=1)

Then you just need to reduce the space between the two plots.

morgan121
  • 2,213
  • 1
  • 15
  • 33
  • Thanks so much! Also to remove the excess space I figured out if you change the border properties on the original graph you can take away the space :) eg: `plot.margin=unit(c(1,1,-0.5,1), "cm")` in the `theme()` section :) – morgan121 Nov 20 '18 at 09:03