R 在ggplot2中仅显示一个文本值
我试图将文本打印限制为条形图中的一个变量。我怎样才能给粉红色的条标上标签呢R 在ggplot2中仅显示一个文本值,r,ggplot2,R,Ggplot2,我试图将文本打印限制为条形图中的一个变量。我怎样才能给粉红色的条标上标签呢601215399456 ggplot(df, aes(Var1, value, label=value, fill=Var2)) + geom_bar(stat="identity", position=position_dodge(width=0.9)) + geom_text(position=position_dodge(width=0.9)) 您可以使用geom_text中的ifelse语句执行此
601215399456
ggplot(df, aes(Var1, value, label=value, fill=Var2)) +
geom_bar(stat="identity", position=position_dodge(width=0.9)) +
geom_text(position=position_dodge(width=0.9))
您可以使用
geom_text
中的ifelse
语句执行此操作。首先,从主ggplot2调用中删除label=value
。然后,在geom_text
中,在标签上添加ifelse
条件,如下所示。此外,如果你避开了不止一种美学,你可以通过创建一个避开对象来节省一些打字
pd = position_dodge(0.9)
ggplot(df, aes(Var1, value, fill=Var2)) +
geom_bar(stat="identity", position=pd) +
geom_text(position=pd, aes(label=ifelse(Var2=="Searches", value,"")))
如果你想要在中间的文本,而不是在顶部,你可以这样做:
geom_text(position=pd, aes(label=ifelse(Var2=="Searches", value, ""), y=0.5*value))
实际上,您可以在主ggplot调用中保留label
语句(添加了ifelse
条件),但由于label
仅适用于geom\u text
(或geom\u label
),我通常将其与geom一起保留,而不是与主调用一起保留
geom_text(position=pd, aes(label=ifelse(Var2=="Searches", value, ""), y=0.5*value))