Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect points in qplot by adjacent y value, not x value

Tags:

r

ggplot2

I make plots of environmental measurements along vertical profiles, e.g. down a sediment core or as a function of depth in the ocean. By convention these plots are presented vertically, with the independent variable (depth) along the y axis. Lines should therefore connect points of adjacent y-value.

The "line" geom in ggplot2 seems only to connect points of adjacent x value. Is there a way around this?

This example creates some realistic-looking data and illustrates the problem:

#generate fake data
sites<-factor(c(rep("site A", 10), rep("site B", 10)))
depths<-rep(1:10, 2)
values<-c(runif(10), runif(10)+2)

#make a visually pleasing scatter plot
qplot(values, depths, geom="point", col=sites)

You can see from that plot that we're looking at measurements related by depth. But:

#make a visually meaningless scatter plot
qplot(values, depths, geom="line", col=sites)

connects the points in a meaningless way. Is there any way to connect the points vertically?

like image 719
Drew Steen Avatar asked Nov 05 '11 08:11

Drew Steen


People also ask

How do I connect dots in ggplot2?

Connecting Paired Points with lines using geom_line() In ggplot2 we can add lines connecting two data points using geom_line() function and specifying which data points to connect inside aes() using group argument. Now we get a scatter plot connecting paired data with lines.

Which ggplot2 connects multiple operations?

Integrating the pipe operator with ggplot2 We can also use the pipe operator to pass the data argument to the ggplot() function. The hard part is to remember that to build your ggplot, you need to use + and not %>% . The pipe operator can also be used to link data manipulation with consequent data visualization.

What does GG in Ggplot represent?

The ggplot2 package is a relatively novel approach to generating highly informative publication-quality graphics. The “gg” stands for “Grammar of Graphics”.

Which layer in ggplot2 is used to define the X axis and Y axis?

The aesthetic layer maps variables in our data onto scales in our graphical visualization, such as the x and y coordinates. In ggplot2 the aesthetic layer is specified using the aes() function. Let's create a plot of the relationship between Sepal. Length and Sepal. Width, putting them on the x and y axis respectively.


1 Answers

qplot(depths, values, geom="line", group=sites) + coord_flip()

enter image description here

like image 91
John Colby Avatar answered Sep 30 '22 10:09

John Colby