2d density plots

By Data Tricks, 15 June 2018

Create data and set-up theme

library(ggplot2)
set.seed(555)
data <- data.frame(
Value1 = rnorm(100000, 500, 200),
Category = rep(c("One", "Two", "Three", "Four"), each=1, times=25000),
Random = rnorm(100000, 100, 100),
Size = sample(1:10, 100000, replace = TRUE)
)
data$Value2 <- data$Value1 + data$Random
data$Size2 <- data$Value1 * data$Size
theme <- theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
axis.line.x = element_line(color="#919191", size = 0.1),
axis.line.y = element_line(color="#919191", size = 0.1))

2D density plot

#Density 2d
gg <- ggplot(data, aes(x = Value1, y = Value2))
gg <- gg + geom_bin2d()
gg <- gg + xlab("") + ylab("") + theme
print(gg)

2D density plot with custom bins

#Density 2d with custom bins
gg <- ggplot(data, aes(x = Value1, y = Value2))
gg <- gg + geom_bin2d(bins=200)
gg <- gg + xlab("") + ylab("") + theme
print(gg)

2d density plot with customer colours

#Density with custom colours
gg <- ggplot(data, aes(x = Value1, y = Value2))
gg <- gg + geom_hex(bins=150)
gg <- gg + scale_fill_gradient(low='#c80000', high='#FFFF00')
gg <- gg + xlab("") + ylab("") + theme
print(gg)

Tags: , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Please note that your first comment on this site will be moderated, after which you will be able to comment freely.