user2955884
user2955884

Reputation: 551

Weird result of facet_wrap() with geom_density_2d()

Given:

#Data: https://www.dropbox.com/s/sk7uqfzp9t7gki5/test.rda?dl=0
load("test.rda")
summary(test)
table(test$Date, test$Treatment)

why is this:

#why is this:
ggplot(data=test,aes(x=PC1, y=PC3, color=Treatment)) + 
  geom_density_2d() +
  theme(aspect.ratio=1) +
  facet_wrap(~Date)

different to this:

#different than this:
test1 <- test[test$Treatment=="B1G1",]
test2 <- test[test$Treatment=="B1G0",]
test3 <- test[test$Treatment=="B0G0",]
ggplot(data=test,aes(x=PC1, y=PC3, color=Treatment)) + 
  geom_density_2d(data=test1) +
  geom_density_2d(data=test2) +
  geom_density_2d(data=test3) +
  theme(aspect.ratio=1) +
  facet_wrap(~Date)

I want the 2nd plot but with a syntax similar to the 1st one. I think this is related to something in the actual data (thus I provide the link) but cannot figure out what.

Upvotes: 0

Views: 253

Answers (1)

user2955884
user2955884

Reputation: 551

Thanks to the comment by Santiago I. Hurtado: specifying bins within geom_density_2d(bins=25) considerably alleviates the problem:

ggplot(data=test,aes(x=PC1, y=PC3, color=Treatment)) + 
  geom_density_2d(bins=25) +
  theme(aspect.ratio=1) +
  facet_wrap(~Date)

But actually, a better solution is provided by clauswilke in https://github.com/tidyverse/ggplot2/issues/4529

ggplot(data=test,aes(x=PC1, y=PC3, color=Treatment)) + 
  geom_density_2d(contour_var="ndensity") +
  theme(aspect.ratio=1) +
  facet_wrap(~Date, scales="free")

Upvotes: 1

Related Questions