Using Different Colors to Group Points by a Variable

In this section, we'll produce a color differentiated scatter plot with respect to a third variable. Let's begin by implementing the following steps:

  1. Choose a subset of dataset 1 (gapminder) and select a few countries. Use the following subset command:
dfs <- subset(df,Country %in%c("Germany","India","China","United States"))
  1. Make a scatter plot of the two variables and change the x and y titles:
p1<- ggplot(df,aes_string(x=var1,y=var2))+)geom_point(color=2,shape=2)+xlim(0,10000)+xlab(name1)+ylab(name2)
  1. Then, change the colors and shapes of the points for plot 1:
p2 <- ggplot(df,aes_string(x=var1,y=var2))+geom_t(aes(color=Country,shape=Country))+xlim(0,10000)+xlab(name1)+ylab(name2) ...

Get Applied Data Visualization with R and ggplot2 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.