代码之家  ›  专栏  ›  技术社区  ›  aaaaa

从几何点和比例填充渐变向图例添加一个点

  •  2
  • aaaaa  · 技术社区  · 7 年前

    已经有几个月的时间了 ggplot2 但我还是很容易被困在基本的事情上,因为这里的选项几乎是无限的。

    set.seed(100)
    df_1 = data.frame(lat = rnorm(20), 
                      lon = rnorm(20), 
                      x = rnorm(20))
    
    
    library(ggplot2)
    p = ggplot() +
    
        geom_point(data = df_1, 
               aes(x=lon, y=lat, fill = x), 
               size = 5, colour = 'black', pch = 21) +
    
        scale_fill_gradient2(low = "green", mid = 'white', high = "yellow",
                             breaks = c(-1, 0, 1), 
                             labels = c('-1', '0', '1'),
                             limits = c(-1,1))
    
    print(p)
    

    enter image description here

    如何添加第二个图例,标题(例如y)仅显示其中一个具有白色背景和黑色轮廓的圆?

    2 回复  |  直到 7 年前
        1
  •  3
  •   pogibas    7 年前

    要向图例中添加额外的元素,必须将其添加到绘图中。您可以通过以下方式完成此操作:

    geom_point(aes(alpha = ""), head(df_1, 1),
               size = 5, fill = "white", pch = 21) +
    

    fill 还有假人 alpha 值(我们需要在 aes 将其添加到图例中)。我在用 "" 所以我们不会有任何文字旁边的一点。
    另外,在主要问题之前添加这一点也很重要 geom_point 阿尔法 值来自 1 并为其设置通缉的传奇名字 阿尔法 在里面 labs() .

    library(ggplot2)
    ggplot(df_1, aes(lon, lat, fill = x)) +
        geom_point(aes(alpha = ""), head(df_1, 1),
                   size = 5, fill = "white", pch = 21) +
        geom_point(size = 5, pch = 21) +
        scale_fill_gradient2(low = "green", mid = "white", high = "yellow",
                             breaks = c(-1, 0, 1), 
                             labels = c("-1", "0", "1"),
                             limits = c(-1, 1)) +
        scale_alpha_manual(values = 1) +
        labs(alpha = "y")
    

    enter image description here


    另外,我对你的简历做了一些修改 ggplot2 代码:

    • aes公司 在第一个 ggplot
    • 在几何图层中 aes公司 是第一个参数,数据是第二个参数。所以 geom_point(data = df_1, aes(...) . 你有用处 geom_point(aes(...), df_1) .
    • color = "black"
        2
  •  1
  •   LAP    7 年前

    您可以添加一个具有一个级别的因子并使用 scale_color_manual :

    set.seed(100)
    df_1 = data.frame(lat = rnorm(20), 
                      lon = rnorm(20), 
                      x = rnorm(20),
                      new = rep('Coordinates', 20))
    
    
    library(ggplot2)
    p = ggplot() +
    
      geom_point(data = df_1, 
                 aes(x=lon, y=lat, fill = x, colour = new), 
                 size = 5, pch = 21) +
      scale_fill_gradient2(low = "green", mid = 'white', high = "yellow",
                           breaks = c(-1, 0, 1), 
                           labels = c('-1', '0', '1'),
                           limits = c(-1,1)) +
      scale_color_manual(name = "", values = "black")
    
    print(p)
    

    enter image description here

    推荐文章