使用bquote函数的geom_text / geom_label

3

我的数据:

dat <- data_frame(x = c(1,2,3,4,5,6), y = c(2,2,2,6,2,2))

我希望能在点(x=4,y=6)旁边显示这个表达式:
expression <- bquote(paste(frac(a[z], b[z]), " = ", .(dat[which.max(dat$y),"y"] %>% as.numeric())))

但是,当我在使用ggplot时使用这个表达式:
ggplot() + 
  geom_point(data = dat, aes(x = x, y = y)) + 
  geom_label(data = dat[which.max(dat$y),], aes(x = x, y = y, label = expression))

我收到了这个错误信息:
Error: Aesthetics must be either length 1 or the same as the data (1): label
1个回答

5
你可以使用以下代码(保留你对数据和表达式的定义):
与你的问题无关,但是:最好在ggplot调用中定义美学,并在后续函数调用中重复使用它。如果需要,可以覆盖定义,如下面在geom_label中所做的那样。
ggplot(data = dat, aes(x = x, y = y)) + 
  geom_point() + 
  geom_label(data = dat[4,], label = deparse(expression), parse = TRUE, 
             hjust = 0, nudge_x = .1)
和 用于相对于点的位置标记。可以认为也要使用 来使整个标签显示在图片中。

生成此图:

enter image description here

请告知是否符合您的要求。


1
很高兴能够帮助,我的荣幸。 - KoenV
我不会说在主要的ggplot调用中定义aes几乎总是更好。但最终,我想这也与风格有关。如果您知道所有图都将使用相同的aes - 那么当然,在主要调用中定义它。 - tjebo

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