zoukankan      html  css  js  c++  java
  • 【R】调整ggplot图例大小

    图例太多时,会挤压正图,显得正图展示区域很小,这时有必要缩小图例。

    
    #################
    # 减小ggplot图例
    #################
    
    library(ggplot2)
    p <- ggplot(mtcars, 
                aes(drat, mpg, color = factor(gear), shape = factor(vs))) +
      geom_point(size = 2) +
      theme_classic() +
      theme(legend.position = c(0.1, 0.7))
    p
    
    # Overwrite given size (2) to 0.5 (super small)
    p <- p + guides(shape = guide_legend(override.aes = list(size = 0.5)))
    p
    
    p <- p + guides(color = guide_legend(override.aes = list(size = 0.5)))
    p
    
    p <- p + theme(legend.title = element_text(size = 3), 
                   legend.text = element_text(size = 3))
    p
    
    addSmallLegend <- function(myPlot, pointSize = 0.5, textSize = 3, spaceLegend = 0.1) {
      myPlot +
        guides(shape = guide_legend(override.aes = list(size = pointSize)),
               color = guide_legend(override.aes = list(size = pointSize))) +
        theme(legend.title = element_text(size = textSize), 
              legend.text  = element_text(size = textSize),
              legend.key.size = unit(spaceLegend, "lines"))
    }
    
    # Apply on original plot
    addSmallLegend(p)
    
    
    ##################
    # 折叠图例文本
    ##################
    
    a <- (1:10)
    b <- c(1,1.5,2,4,5,5.3,7,9,9.5,9.8)
    places = c("Birmingham","Chester-le-street","Cambridge", "Newcastle-upon-Tyne","Peterborough","Cambridge", "Newcastle-upon-Tyne","Peterborough","Liverpool","Stratford-upon-Avon")
    df1 = data.frame(a,b,places)
    
    library(ggplot2)
    p <- ggplot(df1, aes(x=a, y=b)) + geom_point(aes(colour = places), size=3)
    p
    
    #指定图例列数
    library(scales)
    p + guides(colour = guide_legend(nrow = 2))
    p
    
    
    ##或换行
    df1$places<-sub("-", "- \n ", df1$places)  
    p = ggplot(df1, aes(x=a, y=b)) + geom_point(aes(colour = places), size=3)
    p
    
    
  • 相关阅读:
    Scripts.Render 索引超出了数组界限
    AutoFac使用方法总结
    MFC中打开一个获取路径的对话框
    MFC中自定义消息
    获得窗口句柄的方法
    App Doc View Frame中指针的获取
    MFC中菜单的命令响应顺序
    机械设计软件编写心得
    对SVD奇异值分解的理解
    安装win8+Ubuntu14.04双系统的经验总结
  • 原文地址:https://www.cnblogs.com/jessepeng/p/11454520.html
Copyright © 2011-2022 走看看