Home > front end >  Remove a default segment from ggplot
Remove a default segment from ggplot

Time:09-30

Can I remove the solid black line that connects the x-axis to the density line on the top?

Here is my code

a <- 10
b <- 30
ggplot(data.frame(x = c(a,b)), aes(x = x))   
  stat_function(fun = dunif, args = list(min = a, max = b))  
  theme_bw()  
  labs(x = "\n x", y = "f(x) \n", title = "Uniform Distribution (10,30) \n")  
  theme(plot.title = element_text(hjust = 0.5))  
  geom_segment(x=10, y=0, xend=10, yend=.05, lty = 'dotted')  
  geom_segment(x=30, y=0, xend=30, yend=.05, lty = 'dotted')   
  geom_segment(x=20, y=0, xend=20, yend=.05, lty = 'dashed', colour = 'blue')  
  geom_segment(x=(20 20/3*sqrt(3)), y=0, xend=(20 20/3*sqrt(3)), yend=.05, lty = 'dashed', colour = 'red')  
  geom_segment(x=(20-20/3*sqrt(3)), y=0, xend=(20-20/3*sqrt(3)), yend=.05, lty = 'dashed', colour = 'red')  
  xlim(5,35)

I just annotated the unwanted segments. Also, I don't understand why the lines are not perpendicular to the x-axis.

Thanks for your help !!

enter image description here

CodePudding user response:

stat_function samples your function at fixed points along the x axis and draws a single continuous line through the resulting y values. This is why the line is there. The default sample size is 100, meaning there are 100 y values sampled across your plot. This is a small enough number to show a slight slope if you have a large discontinuity on the y axis. Setting n = 1000 will make the lines vertical.

However, to get the vertical lines to disappear altogether, we need the function to output an NA when it is at (or is very close to) the discontinuity. This means we need to wrap dunif in a little custom function as well as increasing the value of n

ggplot(data.frame(x = c(a,b)), aes(x = x))   
  stat_function(fun = function(x) ifelse(abs(x - a) < 0.01 | abs(x - b) < 0.01, 
                                         NA, dunif(x, a, b)), 
                 n = 10000)  
  theme_bw()  
  labs(x = "\n x", y = "f(x) \n", title = "Uniform Distribution (10,30) \n ")  
  theme(plot.title = element_text(hjust = 0.5))  
  geom_segment(x=10, y=0, xend=10, yend=.05, lty = 'dotted')  
  geom_segment(x=30, y=0, xend=30, yend=.05, lty = 'dotted')   
  geom_segment(x=20, y=0, xend=20, yend=.05, lty = 'dashed', colour = 'blue')  
  geom_segment(x=(20 20/3*sqrt(3)), y=0, xend=(20 20/3*sqrt(3)), 
               yend=.05, lty = 'dashed', colour = 'red')  
  geom_segment(x=(20-20/3*sqrt(3)), y=0, xend=(20-20/3*sqrt(3)), 
               yend=.05, lty = 'dashed', colour = 'red')  
  xlim(5,35)

enter image description here

  • Related