ggplot:geom_text和ggplot之间的冲突(填充)

时间:2015-05-10 02:06:56

标签: r ggplot2

当我在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")

1 个答案:

答案 0 :(得分:4)

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

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=

禁用文字图层中的fill=NULL美学
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")