使用`R`中的`ggplot2`包在图例上方添加文本

cnh2zyt3  于 2023-07-31  发布在  其他
关注(0)|答案(2)|浏览(100)

下面的示例代码生成给定的图:

p <- ggplot(data=dat,
    aes(x=X, y=Y, ymin=lo, ymax=hi,
        shape=task, colour=task)) +
    geom_point(size=3, position=position_dodge(0.5)) +
    geom_errorbar(width=0.12, linewidth=0.5, position=position_dodge(0.5)) +
    scale_shape_manual(values=c(16,17),
        labels=c('A', 'B')) +
    scale_colour_brewer(palette='Dark2',
        labels=c('A', 'B')) +
    scale_x_discrete('X',
        labels=c(1, 2, 3, 4)) +
    scale_y_continuous('Y', limits=c(6.0, 8.0),
        breaks=c(6.0, 6.5, 7.0, 7.5, 8.0)) +
    guides(colour=guide_legend(title='Task:'),
        shape=guide_legend(title='Task:')) +
    ggtitle('Title') +
    theme(plot.title=element_text(hjust=0.5),
        axis.text=element_text(size=12),
        axis.title=element_text(size=14),
        legend.text=element_text(size=10)) +
    annotate(geom='text', x=1, y=8, label='1.0', color='black') +
    annotate(geom='text', x=2, y=8, label='0.93', color='black') +
    annotate(geom='text', x=3, y=8, label='0.95', color='black')
p

字符串


的数据
我怎么能在红色标记的地方添加一些文字?谢谢你,谢谢

pcww981p

pcww981p1#

我想到了两个选择:

ggplot(mtcars, aes(mpg, disp, color = factor(cyl))) +
  geom_point() +
  annotate("text", x=Inf, y=Inf, label="QUUX", hjust=0, vjust=1) + 
  coord_cartesian(clip = "off")

字符串


的数据

ggplot(mtcars, aes(mpg, disp, color = factor(cyl))) +
  geom_point() +
  scale_y_continuous(sec.axis = sec_axis(~ ., breaks = max, labels = \(z) "QUUX")) +
  theme(axis.ticks.y.right = element_blank())


hrysbysz

hrysbysz2#

另一个选项是关闭剪裁并使用自定义注解:

p + 
  coord_cartesian(clip = "off") +
  annotation_custom(grid::textGrob("My text", x = 1.05, y = 0.95))

字符串


的数据
这里,X和y坐标是相对于绘图面板(即,灰色矩形),使得x = 0是左边缘,x = 1是右边缘。因此,值1.05将超出绘图面板的右边缘。

所用数据(从所讨论的图中近似推断)

dat <- data.frame(X = as.character(rep(1:4, each = 2)), 
           Y = c(6.3, 6.6, 6.4, 6.7, 6.5, 6.8, 6.6, 6.8),
           lo = c(6.1, 6.4, 6.2, 6.5, 6.3, 6.6, 6.4, 6.6),
           hi = c(6.5, 6.8, 6.6, 6.9, 6.7, 7, 6.8, 7),
           task = rep(LETTERS[1:2], 4))

相关问题