您的位置: 小一的美食厨房 > 文摘

R语言之plotly包——密度图

2019-09-30来源:小一的美食厨房

library(plotly)


#1.简单密度图

density <- density(iris$Sepal.Length) #计算变量密度

#density中的x表示变量的数值。Y表示变量对应的密度


p <- plot_ly(x = ~density$x, y = ~density$y, type = 'scatter', mode = 'lines', fill = 'tozeroy') %>%

  layout(xaxis = list(title = 'Sepal.Length'),

         yaxis = list(title = 'Density'))

p


#2.多元密度图

iris1 <- iris[which(iris$Species == "setosa"),]

density1 <- density(iris1$Sepal.Length)


iris2 <- iris[which(iris$Species == "versicolor"),]

density2 <- density(iris2$Sepal.Length)


iris3 <- iris[which(iris$Species == "virginica"),]

density3 <- density(iris3$Sepal.Length)


p <- plot_ly(x = ~density1$x, y = ~density1$y, type = 'scatter', mode = 'lines', name = 'setosa', fill = 'tozeroy') %>%

  add_trace(x = ~density2$x, y = ~density2$y, name = 'versicolor', fill = 'tozeroy') %>%

  add_trace(x = ~density3$x, y = ~density3$y, name = 'virginica', fill = 'tozeroy') %>%

  layout(xaxis = list(title = 'Sepal.Length'),

         yaxis = list(title = 'Density'))


p


#3.变换颜色(上图颜色太丑,可以修改)

#参考网站:https://www.917118.com/tool/color_3.html


iris1 <- iris[which(iris$Species == "setosa"),]

density1 <- density(iris1$Sepal.Length)


iris2 <- iris[which(iris$Species == "versicolor"),]

density2 <- density(iris2$Sepal.Length)


iris3 <- iris[which(iris$Species == "virginica"),]

density3 <- density(iris3$Sepal.Length)


p <- plot_ly(x = ~density1$x, y = ~density1$y, type = 'scatter', mode = 'lines', name = 'setosa', fill = 'tozeroy',

             fillcolor = 'rgba(168, 216, 234, 0.5)',

             line = list(width = 0.5)) %>%

  add_trace(x = ~density2$x, y = ~density2$y, name = 'versicolor', fill = 'tozeroy',

            fillcolor = 'rgba(255, 212, 96, 0.5)') %>%

  add_trace(x = ~density3$x, y = ~density3$y, name = 'virginica', fill = 'tozeroy',

            fillcolor = 'rgba(100,149,237,0.5)') %>%

  layout(xaxis = list(title = 'Sepal.Length'),

         yaxis = list(title = 'Density'))


p


#4.去掉边缘线mode = 'none'并去掉line的设定

iris1 <- iris[which(iris$Species == "setosa"),]

density1 <- density(iris1$Sepal.Length)


iris2 <- iris[which(iris$Species == "versicolor"),]

density2 <- density(iris2$Sepal.Length)


iris3 <- iris[which(iris$Species == "virginica"),]

density3 <- density(iris3$Sepal.Length)


p <- plot_ly(x = ~density1$x, y = ~density1$y, type = 'scatter', mode = 'none', name = 'setosa', fill = 'tozeroy',

             fillcolor = 'rgba(168, 216, 234, 0.5)') %>%

  add_trace(x = ~density2$x, y = ~density2$y, name = 'versicolor', fill = 'tozeroy',

            fillcolor = 'rgba(255, 212, 96, 0.5)') %>%

  add_trace(x = ~density3$x, y = ~density3$y, name = 'virginica', fill = 'tozeroy',

            fillcolor = 'rgba(100,149,237,0.5)') %>%

  layout(xaxis = list(title = 'Sepal.Length'),

         yaxis = list(title = 'Density'))


p


#参考网站:https://plot.ly/r/filled-area-plots/


本文由小一的美食厨房整理,内容仅供参考,未经书面授权禁止转载!图片来源图虫创意,版权归原作者所有。