ptv-dawe
ptv-dawe

Reputation: 73

Plotting a step function with only horizontal lines

I use ggplot2 to plot a step function using geom_step(). What I need now is to get rid of the vertical lines. This should be a quite common problem in math at least...

The docs do not mention such possibility .

Is there a hidden argument somewhere, or do I need to convert the data somehow so I can print individual lines for each datapoint?

TL;DR:

have ggplot(data,aes(x,y))+geom_step()

want ggplot(data,aes(x,y))+geom_step(lines=horizontal)

Upvotes: 7

Views: 7160

Answers (2)

Benjamin Kraemer
Benjamin Kraemer

Reputation: 31

You can use geom_line with a group argument instead.

ggplot(data,aes(x,y,group=as.factor(x)))+geom_line()

Upvotes: 2

Adrian
Adrian

Reputation: 3308

Read through this example. You may want to remove the vline and play with the various parameters -- see http://docs.ggplot2.org/current/.

library(ggplot2)
df <- data.frame(x=seq(0, 10), y=cumsum(rnorm(11)))
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 segments
p

output from ggsave

Upvotes: 9

Related Questions