r – 如何让ggplot2中的图例与我的情节高度相同?

前端之家收集整理的这篇文章主要介绍了r – 如何让ggplot2中的图例与我的情节高度相同?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用ggplot2(版本0.9.3.1)在R(版本R版本3.0.1(2013-05-16))中生成了一个简单的图,显示了一组数据的相关系数.目前,绘图右侧的图例颜色条是整个绘图大小的一部分.

我希望图例颜色条与图表的高度相同.我以为我可以使用legend.key.height来做到这一点,但我发现事实并非如此.我调查了网格包单元功能,发现那里有一些标准化单元,但是当我尝试它们时(单位(1,“npc”)),颜色条太高了,离开了页面.

如何使图例与图块本身的高度相同?

一个完整的自包含示例如下:

  1. # Load the needed libraries
  2. library(ggplot2)
  3. library(grid)
  4. library(scales)
  5. library(reshape2)
  6.  
  7. # Generate a collection of sample data
  8. variables = c("Var1","Var2","Var3")
  9. data = matrix(runif(9,-1,1),3,3)
  10. diag(data) = 1
  11. colnames(data) = variables
  12. rownames(data) = variables
  13.  
  14. # Generate the plot
  15. corrs = data
  16. ggplot(melt(corrs),aes(x = Var1,y = Var2,fill = value)) +
  17. geom_tile() +
  18. geom_text(parse = TRUE,aes(label = sprintf("%.2f",value)),size = 3,color = "white") +
  19. theme_bw() +
  20. theme(panel.border = element_blank(),axis.text.x = element_text(angle = 90,vjust = 0.5,hjust = 1),aspect.ratio = 1,legend.position = "right",legend.key.height = unit(1,"inch")) +
  21. labs(x = "",y = "",fill = "",title = "Correlation Coefficients") +
  22. scale_fill_gradient2(limits = c(-1,expand = c(0,0),low = muted("red"),mid = "black",high = muted("blue"))

解决方法

这看起来很棘手,我得到的最接近的是这个,
  1. ## panel height is 1null,so we work it out by subtracting the other heights from 1npc
  2. ## and 1line for the default plot margins
  3.  
  4. panel_height = unit(1,"npc") - sum(ggplotGrob(plot)[["heights"]][-3]) - unit(1,"line")
  5. plot + guides(fill= guide_colorbar(barheight=panel_height))

不幸的是,垂直理由有点偏.

猜你在找的CSS相关文章