如何在ggplot2中手动更改图例中的键标签

Far*_*rel 37 label r key ggplot2

我正准备出版的情节.我创建了一个堆积的盒子图,显示每组患者的频率,这些患者是血清反应阴性的一些复杂积累.图例使用了数据框中的标签,这些标签适合我们正在处理项目但不适合发布的标签.我想将名称更改为读者更快速理解的内容.

例如,运行以下脚本

grp <- gl(n=4,k=20,labels=c("group a","group b","group c", "group d"))
value <- runif(n=80, min=10, max=150)
outcome <- cut(value,2)
data <- data.frame(grp,value,outcome)
ggplot(data, aes(grp, fill=outcome)) + geom_bar() +xlab("group") 
             +ylab("number of subjects") + labs(fill="Serologic response")
Run Code Online (Sandbox Code Playgroud)

该代码创建了不适合发布的关键标签"(10.4,80)"和"(80,150)".相反,我希望"双重否定"和"对a和/或b为正".

我想我可以回到数据框并转换为获得具有正确标签的新变量.或者我可以重新考虑我的因素?但是,我更愿意在绘图时这样做.

Bri*_*ggs 38

标准方法是使用缩放功能更改组的显示标签.您可以用.替换您的ggplot电话

ggplot(data, aes(grp, fill=outcome)) + geom_bar() +xlab("group") +
  ylab("number of subjects") + 
  scale_fill_discrete("Serologic response", 
                      breaks=c("(10.1,79.9]","(79.9,150]"), 
                      labels=c("double negative", "positive for a and/or b"))
Run Code Online (Sandbox Code Playgroud)

请注意,比例的标题已合并到scale_fill_discrete通话中.如果您愿意,也可以使用轴执行此操作

ggplot(data, aes(grp, fill=outcome)) + geom_bar() +
  scale_x_discrete("group") +
  scale_y_continuous("number of subjects") + 
  scale_fill_discrete("Serologic response", 
                      breaks=c("(10.1,79.9]","(79.9,150]"), 
                      labels=c("double negative", "positive for a and/or b"))
Run Code Online (Sandbox Code Playgroud)


Far*_*rel 24

我发现了一种混合方式.它确实重新考虑了因素,但我不必在数据框中这样做.相反,我只是在ggplot命令中执行此操作.

ggplot(data, aes(grp, fill=factor(outcome,labels=c("low","high")))) + 
  geom_bar() +xlab("group") +ylab("number of subjects") +
   labs(fill="Serologic response")
Run Code Online (Sandbox Code Playgroud)

还有其他方法吗?