Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/security/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在ggplot2中仅显示一个文本值_R_Ggplot2 - Fatal编程技术网

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))