简体   繁体   English

在ggplot object、R中调整图例标题position

[英]Adjusting legend title position in ggplot object, R

In the following example I am using factoextra and FactoMineR to create a biplot.在以下示例中,我使用factoextraFactoMineR创建双标图。 The plot has a colour bar and the title is technically centered in the middle, but it is in the middle of the colour bar and the tick numbers inclusive, making it look too low, particularly when I have another legend next to it. plot 有一个彩条,标题在技术上居中于中间,但它位于彩条和刻度数字的中间,使其看起来太低,特别是当我旁边有另一个图例时。

library("factoextra")
library("FactoMineR")

data("decathlon2")
df <- decathlon2[1:23, 1:10]

res.pca <- PCA(df,  graph = FALSE)

p<-fviz_pca_var(res.pca, col.var="contrib", 
             gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"),
             repel = TRUE)+
  theme(legend.position='bottom')

p$labels$colour<-'Contribution to variance'

在此处输入图像描述

I would like to raise it, and I have tried using +guides(colour=guide_legend(title.vjust = 0.5))我想提出来,我试过使用+guides(colour=guide_legend(title.vjust = 0.5))

p<-fviz_pca_var(res.pca, col.var="contrib", 
             gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"),
             repel = TRUE)+
  theme(legend.position='bottom')+
  guides(colour=guide_legend(title.vjust = 0.5))

p$labels$colour<-'Contribution to variance'

But this gets rid of the colour bar in exchange for letters.但这摆脱了颜色条以换取字母。 Can anyone help solve this?谁能帮忙解决这个问题? FYI the plot is a ggplot object. Thank you仅供参考,plot 是一个ggplot object。谢谢

在此处输入图像描述

You need to use guide_colourbar() rather than guide_legend() when trying to modify it: 尝试修改它时,您需要使用guide_colourbar()而不是guide_legend()

p <- fviz_pca_var(res.pca, col.var = "contrib", 
                gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"),
                repel = TRUE)+
    # You can use labs() to set labels
    labs(colour = "Contribution to variance") +
    guides(colour = guide_colourbar(title.vjust = 0.9)) +
    theme(legend.position = 'bottom')
print(p)

You can use the legend.title parameter inside theme() to change adjust the position of the legend title:您可以使用theme()中的legend.title参数更改图例标题的 position:

theme(legend.position = "bottom",
      legend.title = element_text(vjust = 0.75)
      ) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM