Plot geom_line() + geom_point() R

I have the following frame:

 df = data.frame(d = rep(1:3,each=2),
                         x = rep(c(0,1),3),
                         y = c)
 df
  d x   y
1 1 0 0.0
2 1 1 1.0
3 2 0 0.0
4 2 1 1.0
5 3 0 0.0
6 3 1 0.5

I want to get a plot similar to this with my data:

enter image description here

I got it with other data.frames but in this one I have repeated data so I think I am not giving ggplot the correct df input to get it.

Here's the code I used for the previous plot, that is not working for this new frame. Ignore de black line.

 q = ggplot(data=df_Hurwicz, aes(x, y, color=d)) + 
   geom_point() +
   geom_line()

enter image description here

Thanks in advance

Upvotes: 0

Views: 101

Answers (1)

Elio Campitelli
Elio Campitelli

Reputation: 1476

You are close. The trick is either to map color to a categorical data:

library(ggplot2)

df = data.frame(d = rep(1:3,each=2),
                x = rep(c(0,1),3),
                y = c(0, 1, 0, 1, 0, 05))

ggplot(data = df, aes(x, y, color = factor(d))) + 
  geom_point() +
  geom_line()

Or to set the group aesthetic explicitly.

library(ggplot2)

df = data.frame(d = rep(1:3,each=2),
                x = rep(c(0,1),3),
                y = c(0, 1, 0, 1, 0, 05))

ggplot(data = df, aes(x, y, color = d, group = d)) + 
  geom_point() +
  geom_line()

Upvotes: 1

Related Questions