简体   繁体   中英

Create multiple plots in R based on column value but colour plots based on a second column

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.

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)
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. 
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM