gpt4 book ai didi

r - 在条形图中组合 scale_fill_manual 和 scale_x_discrete 时缺少图例

转载 作者:行者123 更新时间:2023-12-04 05:13:57 25 4
gpt4 key购买 nike

以下使用 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"))

最佳答案

除了最后一个 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

关于r - 在条形图中组合 scale_fill_manual 和 scale_x_discrete 时缺少图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14546858/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com