I want to plot VarA by VarB in a line graph using ggplot2, but I want a separate plot for each unique ID value and colour the plots by VarC and change shape of the points by VarD.
I can create the individual plots using the following code:
plot_list <- lapply(split(data.df, data.df$ID), function(x)
{
ggplot(x, aes(x=VarA, y=VarB))
geom_point()
theme_bw()
})
But would like to colour points based on another variable (VarC) and change the shape of the points based on a final variable (VarD).
Variables C and D are both factorial with 2 levels.
CodePudding user response:
ggplot contains aesthetics for colour and point shape, change the aesthetic call to:
aes(x=VarA,
y=VarB,
colour=varC,
shape=varD)
The aesthtic fill is used instead of colour for some geoms, and shape will cause problems if included in geoms that don't use it but this should work for geom_point.
Add facet_wrap to the plot to separate graphs for each value of ID:
facet_wrap(~ID)
CodePudding user response:
plot_list <- lapply(split(data.df.new, data.df.new$Sheep_ID), function(x)
{
ggplot(x, aes(x=VarA, y=VarB, colour = VarC))
geom_point()
theme_bw()
scale_color_manual(values = c("R" = "blue", "E" = "pink")) # Add in specific colour for each factor level.
})