简体   繁体   中英

How to color the density of dots in scatter plot using R

I made a scatter plot by ggplot2 like it

So how to color the overlapping dots based on their counts?

0.07    0.04
0.02    0.12
0.00    0.03
0.14    0.10

I made a scatter plot by ggplot2 like it

例子

but I want to color the density of the dots, I tried adding alpha value but it can not indicate the density well. So how to color the overlapping dots based on their counts?

The data I used looks contain 0.1 million numbers(range from 0 to 1) like this (the first column is x and the second is y):

0.07    0.04
0.02    0.12
0.00    0.03
0.14    0.10

I added alpha value and the plot looks like:

+阿尔法

The code:

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)

I made a scatter plot by ggplot2 like it

例子

but I want to color the density of the dots, I tried adding alpha value but it can not indicate the density well. So how to color the overlapping dots based on their counts?

The data I used looks contain 0.1 million numbers(range from 0 to 1) like this (the first column is x and the second is y):

0.07    0.04
0.02    0.12
0.00    0.03
0.14    0.10

I added alpha value and the plot looks like:

+阿尔法

The code:

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)

There is a library that does this well, called ggpointdensity<\/code><\/a> .

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM