【问题标题】:How to display the interval instead of the middle point in a ggplotly histogram?如何在ggplotly直方图中显示间隔而不是中间点?
【发布时间】:2021-04-15 12:43:13
【问题描述】:

当我使用 ggplotly() 将 ggplot 直方图转换为动态图时,我假设悬停会带来区间的中间点。这对我的公众来说并不直观。我需要它来显示间隔。例如:[x, y) 或类似的东西。我该怎么做?

这里是 Iris 数据集的一个简单示例。

library(tidyverse)
library(plotly)

iris %>% 
  ggplot(
    aes(
      x = Sepal.Length
    )
  ) +
  geom_histogram() -> p 


ggplotly(p)
  

也许还有一件事:当我创建一个 ggplot2 直方图时,我知道我可以控制 bin 的数量和 bin 的大小。有没有办法获得更多控制权,也许手动设置所有内容?

在此先感谢,对于糟糕的英语感到抱歉!

【问题讨论】:

    标签: r ggplot2 plotly histogram ggplotly


    【解决方案1】:

    您可以尝试预先计算 binwidth bw。我为此借用了解决方案here。然后计算休息时间hist_breaks 并使用cut 将间隔添加为aes 中的标签,使用text。

    x <- iris$Sepal.Length
    bw <- 2 * IQR(x) / length(x)^(1/3)
    num_bins <- diff(range(x)) / (2 * IQR(x) / length(x)^(1/3))
    
    hist_breaks <- c(min(x)+ 0.1 - bw/2, rep(bw, num_bins+1)) %>% cumsum()
    
    p <- iris %>% 
      mutate(label =cut(Sepal.Length, hist_breaks)) %>% 
      ggplot(aes(x = Sepal.Length, text = label)) +
        geom_histogram(binwidth = bw)
    ggplotly(p, tooltip = c("count", "text"))
    

    The plot

    使用p + geom_vline(xintercept = hist_breaks)检查边界是否正确

    【讨论】:

      猜你喜欢
      • 2022-12-17
      • 1970-01-01
      • 2018-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      相关资源
      最近更新 更多