2

以下使用 ggplot 不产生图例。我想要一个标识条形图颜色的图例:

df1 <- data.frame(Response = factor(c(1,1,2,2,3,3,4,4)),
                  treatment = factor(c("Active",  "Placebo", "Active",
                  "Placebo", "Active","Placebo","Active","Placebo"),
                                       levels=c("Active","Placebo")),
              percent = c(16.81, 13.53, 17.42, 16.24, 25.33, 19.27,
                          100-16.81-17.42-25.33,100-13.53-16.24-19.25))

# Bar graph, with side-by-side bars
ggplot(data=df1, aes(x=Response, y=percent, fill=treatment, order=treatment)) + 
  geom_bar(stat="identity", position=position_dodge()) + 
  ylab("Percent") + xlab("Outcome") +
  scale_x_discrete(breaks=factor(1:4), labels=c("CR","PR","SD","PD"))+
  scale_fill_manual(values=c("black","red", name="Response", 
                breaks=1:2, labels=c("Active","Placebo"))
4

2 回答 2

3

scale_fill_manual除了最后一部分,你已经得到了一切。出问题的部分是breaks=1:2。但这不是真的,因为您已经设置fill=treatment了这意味着中断设置为levels of treatment. 所以,如果你要设置breaks,它应该是例如,breaks=levels(factor(df1$treatment))(这是多余的)。当然,您可以将标签更改为任何值。例如:

为了不删除图例,您可以做的是:

# No issues changing values of labels for every breaks set
scale_fill_manual(values=c("black","red"), name = "Response",
      breaks = levels(factor(df1$treatment)), 
      labels = c("bla1", "bla2"))

但是,如果您想使用labels设置为 的相同值,这就足够了breaks

scale_fill_manual(values=c("black","red"), name = "Response")

这是整个代码:

p <- ggplot(data = df1, aes(x = Response, y = percent, fill = treatment, 
            order = treatment))
p <- p + geom_bar(stat = "identity", position = position_dodge()) 
p <- p + ylab("Percent") + xlab("Outcome")
p <- p + scale_x_discrete(breaks=factor(1:4), labels=c("CR","PR","SD","PD"))
p <- p + scale_fill_manual(values=c("black","red"), name = "Response", 
         labels = c("Active", "Placebo")) 
# although labels is redundant if you aren't changing its value
p
于 2013-01-27T11:47:54.480 回答
0
ggplot(data=df1, aes(x=Response, y=percent, fill=treatment, order=treatment)) + 
  geom_bar(stat="identity", position=position_dodge()) + 
  ylab("Percent") + xlab("Outcome") +
  scale_x_discrete(breaks=factor(1:4), labels=c("CR","PR","SD","PD")) +
  scale_fill_manual(values=c("black","red"))

在此处输入图像描述

于 2013-01-27T11:51:36.883 回答