【问题标题】:How to color the density of dots in scatter plot using R如何使用R为散点图中的点密度着色
【发布时间】:2018-01-07 21:15:08
【问题描述】:

我用ggplot2做了一个散点图

但我想为点的密度着色,我尝试添加 alpha 值但它不能很好地指示密度。那么如何根据计数对重叠的点进行着色呢?

我使用的数据看起来像这样包含10万个数字(范围从0到1)(第一列是x,第二列是y):

0.07    0.04
0.02    0.12
0.00    0.03
0.14    0.10

我添加了 alpha 值,绘图看起来像:

代码:

library(ggplot2)
p <- ggplot(file, aes(X1,X2)) + geom_point(size=1,alpha = 0.1)
p + labs(x= " " , y=" ", title=" ") + xlim(0.0,1.0) + ylim(0.0,1.0)

【问题讨论】:

  • 您能否分享一个包含您的数据子集或玩具数据的可重现示例?
  • 我显示一些数据,它有 100k 坐标...
  • 我认为@Sal 的意思是您应该提供reproducible R example。请提供导致所呈现情节的代码,并与?dput 分享您的数据(或部分数据)

标签: r ggplot2


【解决方案1】:

为了传达密度信息,点图或散点图可能不是最理想的,因为 alpha 真的很难识别。

在您的情况下查看十六进制图 (http://ggplot2.tidyverse.org/reference/geom_hex.html) 或热图 (http://ggplot2.tidyverse.org/reference/geom_bin2d.html)。

由于我不知道您的数据,我将只使用ggplot2s diamond-dataset。您可以像这样创建上述图(两个示例均取自文档):

library(ggplot2)
ggplot(diamonds, aes(carat, price)) +
 geom_hex()

或者像这样


library(ggplot2)
ggplot(diamonds, aes(carat, price)) +
 geom_bin2d(bins = 100)

附录

我刚刚注意到,您的第二个问题是关于颜色中断的。要允许此使用 scale_fill_viridis_c(breaks = c(100, 500, 1500, 2500, 4000)) 实现此效果。

ggplot(diamonds, aes(carat, price)) +
  geom_bin2d(bins = 100) + 
  scale_fill_viridis_c(breaks = c(100, 500, 1500, 2500, 4000))

reprex package (v0.3.0) 于 2020 年 4 月 20 日创建

【讨论】:

  • 我之前尝试过使用geom_hex,但看起来很糟糕(都是相同的颜色......如何调整计数范围?
  • 例如,您可以使用geom_hex(bins = 10) 或其他bin-number。
  • 以你上面展示的第一张图片为例,右边的计数:5000、4000、3000、2000、1000。如何将它们更改为5000、4000、3000、2000、1000、 800, 600, 400, 200 ?
  • 查看scale_y_continous 和breaks 参数或scale_y_log10,具体取决于您要应用的规模。
【解决方案2】:

我找到了一些方法:

1) Color scatterplot points by density 这个很好用。

2) Josh O'Brien's answer 这太棒了!我也想知道如何呈现密度和颜色的精确值之间的关系...

3)Create smoothscatter like plots with ggplot2这两个也不错。

我不擅长编程,只能在网上找一些别人提供的代码:(

【讨论】:

    【解决方案3】:

    有一个库可以很好地做到这一点,称为ggpointdensity

    它避免了分箱图缺乏平滑性,并且不需要额外计算密度。

    自述文件中的示例:

    library(ggplot2)
    library(dplyr)
    library(viridis)
    library(ggpointdensity)
    
    dat <- bind_rows(
      tibble(x = rnorm(7000, sd = 1),
             y = rnorm(7000, sd = 10),
             group = "foo"),
      tibble(x = rnorm(3000, mean = 1, sd = .5),
             y = rnorm(3000, mean = 7, sd = 5),
             group = "bar"))
    
    ggplot(data = dat, mapping = aes(x = x, y = y)) +
      geom_pointdensity() +
      scale_color_viridis()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-11
      • 1970-01-01
      • 1970-01-01
      • 2021-06-16
      • 2018-09-22
      • 1970-01-01
      • 2013-12-05
      相关资源
      最近更新 更多