使用geom_dotplot绘制点图颜色

时间:2019-01-04 18:50:21

标签: r ggplot2

如何使用data $ color向量使点图点着色?情节上应该有一个红点

t =c(c(10,4,5,6,7,8,15,2),c(2,5,5,14,16,8,15,17))
g =c(  rep("A",8),rep("B",8))

data = data.frame(group = g ,t = t)
data$label = ""
data$label[10]= "g"
data$color =""
data$color[10]= "red"

library(ggplot2)
library(ggrepel)

myfun<- function(x) {
  r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}


 ggplot(data, aes(x=g, y=t,label = label 
)) + theme_bw()+
  stat_summary(fun.data = myfun, geom="boxplot")  +
   geom_dotplot(binaxis='y', stackdir='center', dotsize=.5, color = color)

我收到一条错误消息:找不到对象“颜色”

1 个答案:

答案 0 :(得分:2)

ggplot似乎没有在寻找数据来查找颜色变量,因此您需要告诉它颜色位于何处。这对我有用:

t =c(c(10,4,5,6,7,8,15,2),c(2,5,5,14,16,8,15,17))
g =c(  rep("A",8),rep("B",8))

data = data.frame(group = g ,t = t)
data$label = ""
data$label[10]= "g"
data$color <- 'black' # added this to color the other points
data$color[10]= "red"

library(ggplot2)
library(ggrepel)

myfun<- function(x) {
  r <- quantile(x, probs = c(0.05, 0.25, 0.5, 0.75, 0.95))
  names(r) <- c("ymin", "lower", "middle", "upper", "ymax")
  r
}

ggplot(data, aes(x=g, y=t,label = label)) + theme_bw()+
stat_summary(fun.data = myfun, geom="boxplot")  +
geom_dotplot(aes(fill = color), binaxis='y', stackdir='center', dotsize=.5) + 
scale_fill_identity()

我认为要更改的更好属性是填充,但是您可以将其更改回颜色

编辑了ggplot调用,以纳入有关如何使代码更优雅的建议。