Home > Blockchain >  In ggplot2 is there a relatively simple way of using different geoms for different groups in the dat
In ggplot2 is there a relatively simple way of using different geoms for different groups in the dat

Time:10-19

I have a set of data with multiple groups. I'd like to plot them on the same graph but with, say, a smooth line for one group and the data points for the other. Or with smooth lines for both, but data points for only one of them. An example:

library(reshape)
library(ggplot2)

set.seed(123)
x <- 1:1000
y <- 5   rnorm(1000)
z <- 5   0.005*x   rnorm(1000)

df <- as.data.frame(cbind(x,y,z))
df <- melt(df,id=c("x"))

ggplot(df,aes(x=x,y=value,color=variable))  
geom_point()   #here I want only the y variable graphed
geom_smooth() #here I want only the z variable graphed

They are both graphed against the x variable, and are on the same scale. Is there a relatively easy way to accomplish this?

CodePudding user response:

Set the data parameter with the filtered data on each plot type

library(ggplot2)
library(reshape)
set.seed(123)

x <- 1:1000
y <- 5   rnorm(1000)
z <- 5   0.005*x   rnorm(1000)

df <- as.data.frame(cbind(x,y,z))
df <- reshape::melt(df,id=c("x"))
df
ggplot(df,aes(x=x,y=value,color=variable))  
  geom_point(data=df[df$variable=="y",])   #here I want only the y variable graphed
  geom_smooth(data=df[df$variable=="z",]) #here I want only the z variable graphed
  • Related