【问题标题】:Color histrogram by standard deviation plotly R按标准差绘制的颜色直方图 R
【发布时间】:2018-02-14 23:37:21
【问题描述】:

我正在生成一个表示正态分布数据的直方图。我想根据平均值的标准差为直方图着色(即在一个 SD = 蓝色、2 = 绿色、3 = 橙色内)。

这是我正在使用的代码的 sn-p:

x <- rchisq(1000, 50, 10)
plot_ly(x=x, type="histogram")

【问题讨论】:

    标签: r histogram plotly r-plotly


    【解决方案1】:

    我认为不可能为用户想要的标准偏差精确定义它,但我认为这是使用ggplot2ggplotlyggplotly 函数@ 的一个很好的选择

    x <- rchisq(1000, 50, 10)
    p = qplot(x =x, fill=..count.., geom="histogram",bins=30) +
      scale_fill_gradient(low="orangered2",high="yellow",guide = 'none')+
      theme_bw()+labs(y="")
    ggplotly(p)
    

    【讨论】:

      【解决方案2】:

      正如@Alejandro Andrade 提到的,plot_ly 可能无法实现,但如果你真的想要三种颜色,你可以欺骗它并使用 geom_bar。你可以试试:

      #Create aplot and then extract the data
      a <- ggplot(data=x, aes(x)) + geom_histogram()
      temp <- layer_data(a, 1)
      
      #calculate the mean and sd you want. Just an example
      mean_vt <- mean(temp$x)
      sd_vt <- sd(temp$x)
      sd_vt2 <- 2*sd(temp$x)
      sd_vt3 <- 3*sd(temp$x)
      
      #create a new category for colors
      temp$Color <- 
          ifelse(temp$x >= (mean_vt-sd_vt) & temp$x <= (mean_vt+sd_vt), "SD1", 
          ifelse(temp$x >= (mean_vt-sd_vt2) & temp$x <= (mean_vt+sd_vt2), "SD2", 
                  ifelse(temp$x >= (mean_vt-sd_vt3) & temp$x <= (mean_vt+sd_vt3), "SD3",         
      "NA")))
      
      #and then plot using ggplotly
      pp <- ggplot(data = temp, aes(x =x,y=y, fill=Color)) + 
        geom_bar(stat = 'identity', width = 2.5) +
        scale_fill_manual(values = c("blue", "green", "orange"))
      
      ggplotly(pp)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-09-07
        • 1970-01-01
        • 2014-05-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多