在ggplot图表中使用两个标签的geom_text

5

我遇到了一个问题,想在我的ggplot图表上添加一个额外的标签。

这是我的数据集:

Group                   Gaze direction  Counts   Duration
Expert Performers       game table      148      1262.122
Expert Performers       objects table   40       139.466
Expert Performers       other           94       371.191
Expert Performers       co-participant  166      387.228
Non-Performers          game table      223      1137.517
Non-Performers          objects table   111      369.26
Non-Performers          other           86       86.794
Non-Performers          co-participant  312      566.438

这是我使用的代码:

这是我正在使用的代码:

ggplot(b, aes(x=Group, y=Gaze.direction))+
  geom_count(mapping=aes(color=Counts, size=Duration))+
  theme_bw()+
  theme(panel.grid.major = element_line(colour = "grey"))+scale_size(range = c(0, 8))+
  scale_colour_gradient(low = "black", high = "gray91")+
  scale_y_discrete(name ="Gaze direction") + 
  geom_text(aes(label=Counts,hjust=-1, vjust=-1))

当前图形:

期望的图形应该包含每个数据点的计数数量(已经有了),并且还应该用括号(在图中标为红色)显示持续时间。

期望的图形:

如果有人知道如何修复我的代码,我会非常感激。

1个回答

14
请将您的数据作为dput()输出发布!
你可以尝试这个:
library(ggplot2)
b <- data.frame(Group  = c("Expert Performers","Expert Performers","Expert Performers","Expert Performers","Non-Performers","Non-Performers","Non-Performers","Non-Performers"), 
                   Gaze.direction = c("game table","objects table","other","co-participant","game table","objects table","other","co-participant"), Counts = c(148,40,94,166,223,111,86,312), Duration =c(1262.122,139.466,371.191,387.228,1137.517,369.26,86.794,566.438))

ggplot(b, aes(x=Group, y=Gaze.direction))+
  geom_count(mapping=aes(color=Counts, size=Duration))+
  theme_bw()+
  theme(panel.grid.major = element_line(colour = "grey"))+scale_size(range = c(0, 8))+
  scale_colour_gradient(low = "black", high = "gray91")+
  scale_y_discrete(name ="Gaze direction") + 
  geom_text(aes(label=paste("(",Counts,",",Duration,")"),hjust=-1, vjust=-1))

我在geom_text()函数中使用了paste()函数,其中实现了你的两个变量值(Counts和Duration)。

输入图像描述


抱歉dput输出的问题,这并非故意。下次我会更加注意。非常感谢您提供的解决方案,它看起来正是我想要的样子。 - Jo-Achna
唯一不足的是我仍然缺少在持续时间后面加上 ms。此外,在括号和计数之间以及其他地方有空格。有没有办法去掉这些空格? - Jo-Achna

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接