Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine Points with lines with ggplot2

Tags:

r

ggplot2

I would like to plot a time series that look like this:

enter image description here

what I plot with:

qplot(Jahr, Wert, data=tu, group = Geschlecht, color = Altersgr) + facet_grid(Geschlecht ~ Land) 

My data looks like this:

  Land   Altersgr Geschlecht Jahr  Wert 1   DE    < 20 J.          m 2000  13.0 2   DE  20-<65 J.          m 2000  25.7 3   DE     65+ J.          m 2000  70.1 4   DE  65-<80 J.          m 2000  44.2 5   DE     80+ J.          m 2000 213.5 6   BB    < 20 J.          m 2000  26.8 

Everything is fine so far. But I have to connect the corresponding points (same color) with a line. I couldn't figure out how to do that. If I use geom_line() I got this result:

enter image description here

Which is not what I want... I just have the feeling I overlook something...

Any suggestions? Thanks for y'all help.

like image 921
Dominik Avatar asked Dec 21 '11 15:12

Dominik


People also ask

How do you draw a line through a point in R?

segment() function in R Language is used to draw a line segment between to particular points. Parameters: x, y: coordinates to draw a line segment between provided points. Here, x0 & y0 are starting points of the line segment and x1 & y1 are ending points of line segment .

How do I add a line in ggplot2?

To create a vertical line using ggplot2, we can use geom_vline function of ggplot2 package and if we want to have a wide vertical line with different color then lwd and colour argument will be used. The lwd argument will increase the width of the line and obviously colour argument will change the color.

What does Geom_point () do in R?

The function geom_point() adds a layer of points to your plot, which creates a scatterplot.

What does Geom_line do in R?

geom_line() connects them in order of the variable on the x axis. geom_step() creates a stairstep plot, highlighting exactly when changes occur. The group aesthetic determines which cases are connected together.


1 Answers

You may find that using the `group' aes will help you get the result you want. For example:

tu <- expand.grid(Land       = gl(2, 1, labels = c("DE", "BB")),                   Altersgr   = gl(5, 1, labels = letters[1:5]),                   Geschlecht = gl(2, 1, labels = c('m', 'w')),                   Jahr       = 2000:2009)  set.seed(42) tu$Wert <- unclass(tu$Altersgr) * 200 + rnorm(200, 0, 10)  ggplot(tu, aes(x = Jahr, y = Wert, color = Altersgr, group = Altersgr)) +    geom_point() + geom_line() +    facet_grid(Geschlecht ~ Land) 

Which produces the plot found here:

enter image description here

like image 92
Peter Avatar answered Oct 07 '22 18:10

Peter