ggplot2 垂直颜色条标题右居中

ggplot2 vertical colorbar title right centered

我正在尝试向我的颜色条图例添加一个垂直居中的标题,但它会将标题堆叠在颜色条的顶部而不是右侧。 我试过添加 position = "right" 但它没有帮助,我试过 vjust,hjust 它也不起作用。

它产生的情节:

我想要什么:

代码:

ggplot(df, aes(x=img_type, y=metric),show.legend = FALSE) +
  geom_point(aes(size = abs_corr, colour=corr))+scale_size(range =c(-0.1,20) )+
  scale_colour_gradient2(
    low = "#7e1952",
    high = "#2f7a9a",
    space = "Lab",
    na.value = "white",
    guide = "colourbar",
    aesthetics = "colour",
    mid = "white",
    limits=c(-1,1), name = "Spearman's Correlation Coefficient"
  )+ guides(size = "none")+
  theme(legend.key.height = unit(2.5, "cm"))+
  guides(fill = guide_colourbar(label.position = "right"))+
  theme(legend.title = element_text(size = 12, angle = 90) )

数据:

   metric   pval    corr img_type abs_corr
1     aes 0.0000  0.6820   T2_TSE   0.6820
2     aes 0.0000  0.7365 T2_FLAIR   0.7365
3     aes 0.0003  0.2412   T1_MPR   0.2412
4     aes 0.0000  0.3510  T1_TIRM   0.3510
5      tg 0.0000  0.4434   T2_TSE   0.4434
6      tg 0.0000  0.8093 T2_FLAIR   0.8093
7      tg 0.0000  0.2813   T1_MPR   0.2813
8      tg 0.0000  0.3513  T1_TIRM   0.3513
9   coent 0.0028 -0.2583   T2_TSE   0.2583
10  coent 0.0008 -0.4210 T2_FLAIR   0.4210

这是一个解决方案,灵感来自
请注意,在问题中你有 fill = guide_colourbar(.) 而它应该是 colour = guide_colourbar(.).

library(ggplot2)

ggplot(df, aes(x=img_type, y=metric),show.legend = FALSE) +
  geom_point(aes(size = abs_corr, colour=corr))+
  scale_size(range =c(-0.1,20) )+
  scale_colour_gradient2(
    low = "#7e1952",
    high = "#2f7a9a",
    space = "Lab",
    na.value = "white",
    guide = "colourbar",
    aesthetics = "colour",
    mid = "white",
    limits=c(-1,1), name = "Spearman's Correlation Coefficient"
  )+ 
  guides(
    size = "none",
    colour = guide_colourbar(title.position = "right")
  )+
  theme(legend.key.height = unit(2.5, "cm"),
        legend.title = element_text(size = 12, angle = 90),
        legend.title.align = 0.5,
        legend.direction = "vertical"
  )


数据

df <-
structure(list(metric = c("aes", "aes", "aes", "aes", "tg", "tg", 
"tg", "tg", "coent", "coent"), pval = c(0, 0, 3e-04, 0, 0, 0, 
0, 0, 0.0028, 8e-04), corr = c(0.682, 0.7365, 0.2412, 0.351, 
0.4434, 0.8093, 0.2813, 0.3513, -0.2583, -0.421), img_type = c("T2_TSE", 
"T2_FLAIR", "T1_MPR", "T1_TIRM", "T2_TSE", "T2_FLAIR", "T1_MPR", 
"T1_TIRM", "T2_TSE", "T2_FLAIR"), abs_corr = c(0.682, 0.7365, 
0.2412, 0.351, 0.4434, 0.8093, 0.2813, 0.3513, 0.2583, 0.421)), class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))