R仿图:Base plot仿geom_density()

  先放geom_density()图层的仿照网址:https://www.r-graph-gallery.com/density_mirror_ggplot2.html

  • 生成数据 
data <- data.frame(
  var1 = rnorm(1000),
  var2 = rnorm(1000, mean=2)
)
  • ggpolot2
ggplot(data, aes(x=x) ) +
  geom_density( aes(x = var1, y = ..density..), fill="#69b3a2" ) +
  geom_label( aes(x=4.5, y=0.25, label="variable1"), color="#69b3a2") +
  geom_density( aes(x = var2, y = -..density..), fill= "#404080") +
  geom_label( aes(x=4.5, y=-0.25, label="variable2"), color="#404080") +
  xlab("value of x")+
  theme_classic()

 

  • Base plot
a<-density(data$var1)
b<-density(data$var2)
plot.new()
plot.window(xlim=c(min(a$x,b$x),max(a$x,b$x)),
                 ylim=c(min(-a$y,-b$y),max(a$y,b$y)))
polygon(x=a$x,y=a$y,col="#69b3a2")
text(x=3,y=0.2,labels="variable 1",col="#69b3a2",cex=1.5)
polygon(x=b$x,y=-b$y,col= "#404080")
text(x=5,y=-0.2,labels="variable 2",col="#404080",cex=1.5)
abline(h=0)
axis(1)
axis(2)
mtext(text="value of x",side=1,adj=0.5,line=2,cex=1.5)
mtext(text="density",side=2,adj=0.5,line=2,cex=1.5)

 

猜你喜欢

转载自www.cnblogs.com/Enjoy-Respect-9527/p/12901774.html