用数字标签覆盖R曲线箱形图

axkjgtzd  于 2023-06-19  发布在  其他
关注(0)|答案(1)|浏览(85)

我发现在R下使用plotly来生成一个箱线图时存在问题,该箱线图由一个数值变量(和/或数值强制为字符)分组:

library(plotly)

colors <- c("red","blue","green","pink","brown")
data.in <- data.frame(Age=25*rnorm(100)+50, IMD=sample(5,100,replace=TRUE))
fig <- plot_ly(data=data.in[data.in$IMD == "1",], y=~Age, type="box", color=I(colors[1]),name="1 - least")
fig <- fig %>% add_trace(data=data.in[data.in$IMD == "2",], y=~Age, type="box", color=I(colors[2]),name="2")
fig <- fig %>% add_trace(data=data.in[data.in$IMD == "3",], y=~Age, type="box", color=I(colors[3]),name="3")
fig <- fig %>% add_trace(data=data.in[data.in$IMD == "4",], y=~Age, type="box", color=I(colors[4]),name="4")
fig <- fig %>% add_trace(data=data.in[data.in$IMD == "5",], y=~Age, type="box", color=I(colors[5]),name="5 - most")
fig <- fig %>% layout(yaxis = list(title = "Age"),
                      xaxis = list(title = "IMD"),
                      boxgap = 0.1, boxgroupgap=0)

此代码在与非数值列一起使用时,会给出一个具有并排框和正确标签的箱线图。但是,前面的代码给出了以下内容:

它似乎在位置0(而不是1)绘制了第一个图,并用带有“5”标签的框覆盖了4处的框。
我已经在R v 4.2.2(MacOS 13.4)上使用plotly 4.10.1和ggplot 2 3.4.2以及R v 4.0.2(x86_64)上使用plotly 4.10.2和gggplot 2 3.4.2进行了尝试,并得到了类似的结果。
首先,这是否是一个错误,如何将数字作为标签的字符处理(底部的标签是数字,而不是我给它们的标签),其次,是否有一种方法可以手动指定框绘制的位置,所以我可以将0到1,将应该在5上的框移到5上,而不是在4上过度绘制?

5lhxktic

5lhxktic1#

奇怪。但一个可能的解决方法是将数值列Map到x上:

library(plotly)

set.seed(123)

colors <- c("red", "blue", "green", "pink", "brown")
data.in <- data.frame(Age = 25 * rnorm(100) + 50, IMD = sample(5, 100, replace = TRUE))
plot_ly(data = data.in[data.in$IMD == 1, ], x = ~IMD, y = ~Age, type = "box", color = I(colors[1]), name = "1 - least") %>%
  add_trace(data = data.in[data.in$IMD == 2, ], x = ~IMD, y = ~Age, type = "box", color = I(colors[2]), name = "2") %>%
  add_trace(data = data.in[data.in$IMD == 3, ], x = ~IMD, y = ~Age, type = "box", color = I(colors[3]), name = "3") %>%
  add_trace(data = data.in[data.in$IMD == 4, ], x = ~IMD, y = ~Age, type = "box", color = I(colors[4]), name = "4") %>%
  add_trace(data = data.in[data.in$IMD == 5, ], x = ~IMD, y = ~Age, type = "box", color = I(colors[5]), name = "5 - most") %>%
  layout(
    yaxis = list(title = "Age"),
    xaxis = list(title = "IMD"),
    boxgap = 0.1, boxgroupgap = 0
  )

相关问题