调整ggplot对象中图例标题的位置,R

时间:2018-07-23 23:56:49

标签: r ggplot2 plot legend

在下面的示例中,我使用factoextraFactoMineR创建一个双线图。该图有一个色条,标题在技术上居中,但在色条中间(包括刻度线在内),使其显得过低,特别是当我旁边有另一个图例时。

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'

enter image description here

我想提出来,并且我尝试使用+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'

但是,这消除了用彩条换字母的麻烦。谁能解决这个问题?仅供参考,该图是一个ggplot对象。谢谢

enter image description here

1 个答案:

答案 0 :(得分:3)

尝试修改时,您需要使用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)