ggplot2颜色&按不同因素塑造

时间:2015-10-27 13:47:26

标签: r ggplot2

我有一个包含2个因子的数据集(MACH& YOU)我喜欢用ggplot2制作一个BoxPlot,并用MACH分割BoxPlot颜色,同时突出显示不同形状和黑色的某些点(你)。

我可以让情节有效但我不能使(你)因素在形状方面更大并使其变黑......而不会影响图表上的所有其他点。 忽略评论的行 - 我只是在玩那些。

我的数据框x的格式为

MEDIAN MACH     YOU        PROD
34.5   tool1    false      ME
33.8   tool1    false      ME
32.9   tool2    true       ME
30.1   tool2    true       ME
33.8   tool2    false.....etc

x<- data.frame(MEDIAN=c(34,32,56,34,45,34,45,33,23), MACH=c("t1","t1","t1","t2","t2","t2","t1","t1","t2"), YOU=c("false","false","false","false","true","true","true","false","false"), PROD="U","U","U","U","U","U","U","U","U")
ggplot(data=x,aes(MACH,MEDIAN ))+ 
    geom_boxplot(fill = "white", colour = "blue")+ 
    theme(panel.grid.minor = element_line(colour = "grey"), plot.title = element_text(size = rel(0.8)),axis.text.x = element_text(angle=90, vjust=1), strip.text.x = element_text(size = 8, colour = "black", face = "bold")) +  
    #geom_abline(colour = "grey80")+ 
    #geom_point(shape = factor(YOURLOTS)), size = 3) + 
    #geom_hline(yintercept=x$TARG_AVG,colour = "green")+ 
    #geom_hline(yintercept=x$TARG_MIN,colour = "red")+ 
    #geom_hline(yintercept=x$TARG_MAX,colour = "red")+ 
    geom_point(alpha = 0.6, position = position_jitter(w = 0.05, h = 0.0), aes(colour=factor(MACH),shape = factor(YOU)), size =3)+

    facet_wrap(~PROD, scales = "free") + 
    ggtitle("MyTitle") + 
    scale_size_area() + 
    xlab("STAGE HIST EQUIPID")+ 
    ylab("yaxis") 

enter image description here

2 个答案:

答案 0 :(得分:1)

如果您想为不同大小的点数制作点数,具体取决于它们的值,您可以在aes(size = factor(YOU))内添加geom_point()

您可以选择为您添加scale_size_discrete(range = c(3, 6))的点的大小范围。在此示例中,最小大小为3,最大值为6.

那将是

ggplot(data = x, aes(MACH, MEDIAN)) + 
    geom_boxplot(fill = "white", aes(color = MACH)) + 
    geom_point(aes(shape = factor(YOU), size = factor(YOU)), color = "black", alpha = 0.6, position = position_jitter(w = 0.05, h = 0.0)) + 
    labs(title = "My Title", x = "Stage Hist Equip ID", y = "y-axis") + 
    scale_size_discrete(range = c(3, 6))

答案 1 :(得分:0)

我会通过使用两个子集和两次调用geom_point()来解决这个问题:

library(ggplot2)

x <- data.frame(MEDIAN = c(34,32,56,34,45,34,45,33,23), 
                MACH   = c("t1","t1","t1","t2","t2","t2","t1","t1","t2"), 
                YOU    = c("false","false","false","false","true","true","true","false","false"), 
                PROD   = c("U","U","U","U","U","U","U","U","U"))

ggplot(data = x, aes(MACH, MEDIAN)) + 
  geom_boxplot(fill = "white", colour = "blue") + 
  geom_point(data = subset(x, YOU != "true"), aes(color = MACH), 
             size = 8, alpha = 0.6, 
             position = position_jitter(w = 0.05, h = 0.0)) +
  geom_point(data = subset(x, YOU == "true"), aes(shape = YOU), 
             color = "black", size = 8, alpha = 0.6,
             position = position_jitter(w = -0.05, h = 0.0)) +
  labs(title = "My Title", x = "Stage Hist Equip ID", y = "y-axis")

Plot