Raffaello Nardin
Raffaello Nardin

Reputation: 151

Create a step graph from a serie of data

I have a dataset that looks something like this

depth <- c(300, 360, 420, 480, 500)
concentration <- c(-31.6, -31.8, -30.5, -34.2, -33.6)

dd <- data.frame(depth, concentration)

with the major difference that my real dataset is 3500 row long. Is there a way to obtain a dataset that will allow me to plot them in a "step" graph instead, i.e. transforming the dataset in something like this that then I can plot?

depth1 <-c(300, 360, 360, 420, 420, 480, 480 ...)
concentration 1 <- c(-31.6, -31.6, -31.8, -31.8, -30.5, -30.5, -34.2...)

?

Upvotes: 1

Views: 318

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 173793

You can do

plot(depth, concentration, type = "s")

enter image description here

Or if you prefer ggplot2, you can use geom_step:

library(ggplot2)

ggplot(dd) + geom_step(aes(x = depth, y = concentration))

enter image description here

If you just want the data transformation that would give you the x,y co-ordinates of the steps, you could do:

dd2 <- data.frame(depth = c(rep(depth, each = 2)[-1], NA), 
                  concentration = rep(concentration, each = 2))

So if you plot it with type = "l", i.e. as a line graph, you get the same result:

plot(dd2$depth, dd2$concentration, type = "l")

enter image description here

Upvotes: 3

Related Questions