Scatterplot with combined colour and shape according to class?

26 views
Skip to first unread message

Steve O'Hagan

unread,
Apr 6, 2017, 7:17:31 AM4/6/17
to ggplot2
Frequently we need to plot data that has too many classes for the number of distinct colours available.

Is there a way to assign different shapes and colours to classes via an appropriate ggplot2 aesthetic? e.g. class A -> blue squares, class B -> red circles, class C -> red squares, class D -> blue circles.

Thus with, say, eigth distinct colours and four distinct shapes one could represent 32 distinct classes.

Cheers,
Steve.

Brandon Hurr

unread,
Apr 6, 2017, 1:00:23 PM4/6/17
to Steve O'Hagan, ggplot2
You can define these classes in your dataframe and put them to use with scale_color_identity and scale_shape_identity.

library(tidyverse)

colors <- palette(rainbow(8))
shapes <- c(16, 15, 17, 18)
times <- c(1,2,3)

combos <- expand.grid(colors, shapes)

index <- rep(seq_len(nrow(combos)), each = 3) #creates a repeated index
combos <- combos[index, ] #store expanded df

example <- 
combos %>%
mutate( x = rep(times, times = nrow(.)/length(times))
, y = runif(nrow(.))
)

ggplot(example, aes(x = x, y=y, color = Var1, shape = Var2, group = interaction(Var1, Var2))) +
geom_point() +
geom_line() + 
scale_color_identity() + 
scale_shape_identity()

--
--
You received this message because you are subscribed to the ggplot2 mailing list.
Please provide a reproducible example: https://github.com/hadley/devtools/wiki/Reproducibility
 
To post: email ggp...@googlegroups.com
To unsubscribe: email ggplot2+unsubscribe@googlegroups.com
More options: http://groups.google.com/group/ggplot2

---
You received this message because you are subscribed to the Google Groups "ggplot2" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ggplot2+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply all
Reply to author
Forward
0 new messages