YQ.Wang YQ.Wang - 1 year ago 53
R Question

Doing path & point plot using qplot()

My data consists of three variables:volume, occ and state. I want to have a volume-occ path & point plot with the paths and points marked by different colours according to the state.
Here is my code:

qplot(occ,volume,data = data,geom=c('path','point'),color=factor(state))+scale_colour_manual(values=c("blue", "orange", "red"))

The outcome is like this:


It seems that the qplot() does not connect the points in the initial order.Because the red points and paths are not connected with others, so are the other two coloured points.
I guess qplot() reordered my data according to the variable 'state', and then plot the path within each state separately.
I also tried the code without the colour arguement:

qplot(occ,volume,data = data,geom=c('path','point'))

The outcome is like this:


This outcome does show the initial path order that I want.
What I want is every point being connected continuously in the initial order just like what outcome2 shows and marked by different colours according to the state variable.
What should I do with my code?

Answer Source

If you set the color to a variable the data are also grouped by this variable. To prevent this set the group attribute manually to a constant. Here is an example:

df <- data.frame(x = 1:20, 
                 y = c(rnorm(10, 5, 2), rnorm(10, 5, 2)), 
                 group = c(rep("a", 10), rep("b", 10) ))

ggplot(df, aes(x = x, y = y, group = 1, col = group))+ geom_path()

The same with qplot:

qplot(x,y,data = df,geom=c('point'),color=factor(group), group = 1)

enter image description here

So just add group = 1 to your code and it will work the way you expect it.