[英]How to format legend using scale_color_discrete in stacked plot and have thousand separators included in the y-axis r
[英]Changing y-axis scale to counts using multiple color scales in stacked bar plot
我有一个DF,如下所示:
fruit <- data.frame(Sample=1:100,
Fruit=c(rep("Apple", 10), rep("Strawberry", 25), rep("Grape", 20),
rep("Watermelon", 15), rep("Lime", 11), rep("Blueberry", 10),
rep("Plum", 9)),
Color=c(rep("Red", 30), rep("Green", 45),
rep("Blue", 25)),
Ripe=c(rep(c(T, F), 50)))+
fruit$Fruit <- factor(fruit$Fruit, unique(fruit$Fruit))+
fruit$Color <- factor(fruit$Color, unique(fruit$Color))
然后,我将条形图绘制为:
library(ggplot2)
ggplot(fruit, aes(Color)) +
geom_bar(stat="count", position="fill",aes(fill=Color, color=Color,alpha=Ripe)) +
scale_y_continuous(labels=scales::percent)+
scale_alpha_discrete(range=c(1,0.6))+
theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank())+
scale_color_manual(values = c("Black", "Black", "Black"))+
guides(fill = guide_legend(override.aes = list(colour = NA)))
结果是:
想要得到的是y轴比例,它是Color变量的观察计数,而不是频率(百分比)。
通过@PoGibas在下面给出的答案,我能够将每种颜色的观测值总数放在每个条形之上...但是我不知道您是否知道如何将每个TRUE的观测值总数n放入每个颜色条中。 在这种情况下,每个条形将有两个n观察值,其中一个在条形之上是每个颜色的总n,在TRUE条之上是对该特定颜色的TRUE n观察...
您的ggplot2
代码有些复杂。 您必须删除scale_y_continuous(labels = scales::percent)
以摆脱百分比。 并删除stat = "count"
, position = "fill"
以获取观测值(即,使用简单的geom_bar()
)。
# Using OPs data
library(ggplot2)
ggplot(fruit, aes(Color, fill = Color, alpha = Ripe)) +
geom_bar(color = "black") +
scale_alpha_discrete(range = c(1, 0.6)) +
theme(axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank()) +
guides(fill = guide_legend(override.aes = list(colour = NA)))
另外,您指定color = Color
,然后用scale_color_manual(values = c("Black", "Black", "Black"))
覆盖它
您也可以使用stat_count
ggplot(fruit,aes(Color)) +
stat_count(aes(x=Color,fill=Color, color=Color,alpha=Ripe),geom = "bar",position = "stack")+
scale_y_continuous()+scale_alpha_discrete(range=c(1,0.6))+
theme(axis.title.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank())+
scale_color_manual(values = c("Black", "Black", "Black"))+
guides(fill = guide_legend(override.aes = list(colour = NA)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.