ggplot:geom_text 和 ggplot(fill) 之间的冲突

ggplot: conflict between geom_text and ggplot(fill)

当我在 ggplot 上使用 geom_text 时,与 ggplot "fill" 选项有冲突。

这里是问题的一个明显例子:

library(ggplot2)
a=ChickWeight
str(a)
xx=data.frame(level=levels(a$Chick),letter=1:50)

# a graph with the fill option alone
x11();ggplot(a, aes(x=Chick, y=weight,fill=Diet))  + geom_boxplot(notch=F) +
stat_summary(fun.y="mean", geom="point", shape=23, size=3, fill="white") +
xlab("Chick") +
ylab("Weight")

# a graph with the geom_text option alone
x11();ggplot(a, aes(x=Chick, y=weight))  + geom_boxplot(notch=F) +
stat_summary(fun.y="mean", geom="point", shape=23, size=3, fill="white") +
geom_text(data=xx, aes(x=level,y=450,label = letter)) +
xlab("Chick") +
ylab("Weight")

# a graph with the two option
x11();ggplot(a, aes(x=Chick, y=weight,fill=Diet))  + geom_boxplot(notch=F) +
stat_summary(fun.y="mean", geom="point", shape=23, size=3, fill="white") +
geom_text(data=xx, aes(x=level,y=1750,label = letter)) +
xlab("Chick") +
ylab("Weight")

如果您只希望填充影响箱线图,请将 aes() 移动到箱线图中。 ggplot() 调用本身中的任何 aes() 美学都将传播到所有层

ggplot(a, aes(x=Chick, y=weight))  + geom_boxplot(aes(fill=Diet), notch=F) +
stat_summary(fun.y="mean", geom="point", shape=23, size=3, fill="white") +
geom_text(data=xx, aes(x=level,y=1750,label = letter)) +
xlab("Chick") +
ylab("Weight")

您还可以使用 fill=NULL

禁用文本层中的 fill= 美学
ggplot(a, aes(x=Chick, y=weight, fill=Diet))  + geom_boxplot(notch=F) +
stat_summary(fun.y="mean", geom="point", shape=23, size=3, fill="white") +
geom_text(data=xx, aes(x=level,y=1750,label = letter, fill=NULL)) +
xlab("Chick") +
ylab("Weight")