R manually set shape by factor

后端 未结 2 1797
粉色の甜心
粉色の甜心 2021-01-17 16:25

Asked this question the other day but no one could visualize my question so ive made an example.

A <- c(\'a\',\'b\', \'c\',\'d\',\'e\')
types <- fa         


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-17 16:42

    If I'm understanding you correctly, there will always be (at most) the five categories "a" - "e", and you want the shapes and colors for these to be consistent across datasets. Here is one way (note: gg_color_hue(...) is from here):

    # set up shapes
    shapes <- c(15,18,16,17,19)
    names(shapes) <- letters[1:5]
    
    # set up colors
    gg_color_hue <- function(n) { # ggplot default colors
      hues = seq(15, 375, length=n+1)
      hcl(h=hues, l=65, c=100)[1:n]
    }
    colors <- gg_color_hue(5)
    names(colors) <- names(shapes)
    
    # original data
    ggplot(ABC, aes(x=B ,y=C ,size=D, colour=types,label=types, shape=types)) +
      geom_point()+geom_text(size=2, hjust=0,colour="black", vjust=0) +
      scale_size_area(max_size=20, "D", breaks=c(100,500,1000,3000,5000))  +
      scale_x_log10(lim=c(0.05,10),breaks=c(0.1,1,10))+ 
      scale_y_continuous(lim=c(0,30000000)) +
      scale_shape_manual(values=shapes) + scale_color_manual(values=colors)
    

    #new data
    DEF <- data.frame(B,C,D,types=factor(c("a","a","a","d","e")))
    ggplot(DEF, aes(x=B ,y=C ,size=D, colour=types,label=types, shape=types)) +
      geom_point()+geom_text(size=2, hjust=0,colour="black", vjust=0) +
      scale_size_area(max_size=20, "D", breaks=c(100,500,1000,3000,5000))  +
      scale_x_log10(lim=c(0.05,10),breaks=c(0.1,1,10))+ 
      scale_y_continuous(lim=c(0,30000000)) +
      scale_shape_manual(values=shapes) + scale_color_manual(values=colors)
    

提交回复
热议问题