【问题标题】:R plotly simple boxplot highlighting the most recent valueR plotly简单的箱线图突出显示最近的值
【发布时间】:2021-05-16 11:46:48
【问题描述】:

我可能有一个简单的问题,但我找不到实现我需要的方法。我有一个简单的箱线图如下:

end_dt <- as.Date("2021-02-12")
start_dt <- end_dt - (nrow(iris) - 1)
dim(iris)
dates <- seq.Date(start_dt, end_dt, by="1 day")
df <- iris
df$LAST_VAL <- "N"
df[3, 'LAST_VAL'] <- "Y"

df1 <- df[,c("Sepal.Length","LAST_VAL")]
df1$DES <- 'Sepal.Length'
colnames(df1) <- c("VALUES","LAST_VAL","DES")

df2 <- df[,c("Sepal.Width","LAST_VAL")]
df2$DES <- 'Sepal.Width'
colnames(df2) <- c("VALUES","LAST_VAL","DES")

df <- rbind(df1, df2)

fig <- plot_ly(df, y = ~VALUES, color = ~DES, type = "box") %>% layout(showlegend = FALSE)  

我现在想做的是为每个箱形图添加一个红色标记,仅针对与 LAST_VAL = "Y" 对应的值。这将允许我查看给定每个图的分布,以查看最新值所在的位置。 我尝试使用https://plotly.com/r/box-plots/ 上的信息,但我不知道该怎么做。 谢谢

【问题讨论】:

    标签: r plotly boxplot r-plotly


    【解决方案1】:

    以下解决方案最终在代码方面有点太长了。但是,它应该给你你所要求的。我认为应该在之后添加箱线图,例如:

    fig <- plot_ly(df[df$LAST_VAL=="Y",], 
                   x=~DES, y = ~VALUES, color = ~DES, type = "scatter", colors='red') %>% 
    layout(showlegend = FALSE) %>% 
    add_boxplot(data = df[df$DES=="Sepal.Length",], x = ~DES, y = ~VALUES, 
                  showlegend = F, color = ~DES,
                  boxpoints = F, fillcolor = 'white', line = list(color = c('blue'))) %>% 
    add_boxplot(data = df[df$DES=="Sepal.Width",], x = ~DES, y = ~VALUES, 
                  showlegend = F, color = ~DES,
                  boxpoints = F, fillcolor = 'white', line = list(color = c('green')))
    

    【讨论】:

    • 谢谢@Pascal!一个后续问题。如果我有比上例中的两个更多的箱线图,有没有办法避免一个一个地添加它们?
    • 我尝试了以下方法,但它不起作用: fig % layout(showlegend = FALSE) %>% add_boxplot(df, x = ~DES, y = ~VALUES, color = ~DES, boxpoints = F)
    • 我还没有找到解决方案
    • 它们的颜色可以相同吗?
    • 哦,是的,相同的颜色不是问题,因为它们位于不同的“列”(意味着多个类别)中
    猜你喜欢
    • 2011-01-30
    • 2023-02-17
    • 2021-03-10
    • 2011-04-19
    • 2015-09-11
    • 1970-01-01
    • 1970-01-01
    • 2017-06-14
    • 2014-08-23
    相关资源
    最近更新 更多