Adding horizontal lines in the plot of a step function

Hello!
I attach graphic, image.jpg, in which I want to draw the line y=0 for x<3 and the line y=1 for x>=8, i.e. the result would be image2.jpg.

These are the instructions for image.jpg.

df <- data.frame(x=Asignaturas, y=solF)
df$xend <- c(df$x[2:nrow(df)],NA)
df$yend <- df$y
p <- (ggplot(df, aes(x=x, y=y, xend=xend, yend=yend)) +
geom_vline(aes(xintercept=x), linetype=2,color="grey") +
geom_point() + # Solid points to left
geom_point(aes(x=xend, y=y), shape=1) + # Open points to right
geom_segment()# Horizontal line
+geom_text(aes(label = paste0(solF,''),vjust = -0.5), color = "black")+ylab("Función de distribucción")+ xlab("Asignaturas"))

p

Does anyone know how to do it?

Thanks


Hi,

You can do this by adding two more segments that represent the top and bottom horizontal line, make sure they start / end outside the area you want to crop, them crop the plot by limiting the x-axis

library(ggplot2)

#Data points
myData = data.frame(
  x = 1:5,
  xend = 2:6,
  y = 1:5,
  yend = 1:5
)

#Horizontal lines
ends = data.frame(
  x = c(0,6),
  xend = c(1,7),
  y = c(0,6),
  yend = c(0,6)
)

#Plot
ggplot(myData) + 
  geom_segment(aes(x=x, y=y, xend=xend, yend=yend)) +
  geom_segment(data = ends, aes(x=x, y=y, xend=xend, yend=yend), color = "red") +
  coord_cartesian(xlim=c(0.8,6.2))

Created on 2021-11-22 by the reprex package (v2.0.1)

Of note: you have to use the coord_cartesian() function to set the limit, because if you would just use the xlim() function it would remove the red lines since they are not fully displayed

Thank you very much!

For any data set, it also works:

extraLines <- data.frame(x = c(-Inf, max(df$x)), xend = c(min(df$x), Inf), y = c(0, max(df$y)), yend = c(0, max(df$y)))

p +
  geom_segment(data = extraLines, aes(x = x, xend = xend, y = y, yend = yend), colour = "red") +
  geom_point(data = filter(extraLines, x > 0), aes(x = x, y=y), colour = "red") + 
  geom_point(data = filter(extraLines, x < max(df$x)), aes(x=xend, y=y), shape = 1, colour = "red")  
1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.