R语言 使用ggplot添加包含选定文本的简单图例

ozxc1zmp  于 2022-12-20  发布在  其他
关注(0)|答案(1)|浏览(90)

假设我有一个简单的df,它的图如下:

df = data.frame(a = c('person1','person2','person3'),
                b = c(10,20,30))


ggplot(df)+aes(x=a,y=b,fill=b)+
  geom_bar(stat='identity')

结果

我希望图例是一个包括(例如)以下短语的框:总计= 60
多谢了。

nbysray5

nbysray51#

你可以用label创建一个annotation。确保通过改变plot.marginclip的坐标来创建一些空间。你可以随意设置。下面是一个可重现的例子:

library(ggplot2)
ggplot(df)+aes(x=a,y=b,fill=b)+
  geom_bar(stat='identity') +
  coord_cartesian(clip = "off") +
  annotate("label", x = Inf, y = 20, hjust = -0.1, label = "TOTAL = 60", size = 3) +
  theme(plot.margin = unit(c(1,5,1,1), "lines"),
        legend.position = 'none')

创建于2022年12月12日,使用reprex v2.0.2
在加载ggtext时,可以使用richtext来旋转注解框,如下所示:

library(ggplot2)
library(ggtext)
ggplot(df)+aes(x=a,y=b,fill=b)+
  geom_bar(stat='identity') +
  coord_cartesian(clip = "off") +
  annotate("richtext", x = Inf, y = 20, vjust = 2, label = "TOTAL = 60", size = 3, angle = 90) +
  theme(plot.margin = unit(c(1,5,1,1), "lines"),
        legend.position = 'none')

创建于2022年12月12日,使用reprex v2.0.2

相关问题