Plotly R阶散点图传奇条目

时间:2018-01-08 23:55:45

标签: r plotly

我以下列方式创建一个情节:

## generate test data
getTestData <- function(seed_val=711, noise=1.0) {
    set.seed(seed_val)
    d <- seq(as.Date('2017/01/01'), as.Date('2017/01/08'), "days")
    first_name <- rep("Jane", 8)
    first_name <- append(first_name, rep("Fred", 8))
    first_name <- append(first_name, rep("Sally", 8))
    y1_vals <- seq(1, 3*8, 1)
    y2_vals <- rnorm(3*8, mean=y1_vals, sd=noise)
    dat <- data.frame(date=d, f_name=first_name, y1=y1_vals, y2=y2_vals,
                  stringsAsFactors = FALSE)
    return(dat)
}

dat <- getTestData()
library(dplyr)
library(plotly)
p1 <- plot_ly(dat, x=~date, y=~y1, color=~f_name,
              type = 'scatter', mode = "lines+markers") %>% 
    layout(yaxis = list(title = "some important y value")) %>% 
    add_trace(y=~y2, name='actual', showlegend=FALSE, 
              type='scatter', mode='lines',
              line=list(width = 2, dash = 'dash'), color=~f_name)

enter image description here

通过f_name分组按字母顺序对图例进行排序,但我希望此顺序为: Jane,Fred,Sally 这是数据框中的原始顺序

这里给出了接受的答案:

Plotly R order legend entries

#Set排序参数注释为FALSE的部分中,现在像数据框这样的订单非常接近我需要的,但这个解决方案是用于饼图。我需要在散点图中重新排序我的图例,它似乎没有可用的排序参数(就像饼图一样)。

1 个答案:

答案 0 :(得分:3)

这是你想要的吗?

dat$f_name <- factor(dat$f_name, levels = c("Jane", "Fred", "Sally"))

plot_ly(dat, x=~date, y=~y1, color=~f_name,
    type = 'scatter', mode = "lines+markers") %>% 
        layout(yaxis = list(title = "some important y value")) %>% 
        add_trace(y=~y2, name='actual', showlegend=FALSE, 
          type='scatter', mode='lines',
          line=list(width = 2, dash = 'dash'), color=~f_name)

enter image description here