代码之家  ›  专栏  ›  技术社区  ›  Lisa Ann

在plotly条形图中映射颜色变量

  •  1
  • Lisa Ann  · 技术社区  · 6 年前

    我试图复制 this 带有我的数据集的条形图,这是一个 xts 对象如下:

    distance <- structure(c(-0.88, 2.61, 3.31, 4.7, 7.49, 0.51, 0.51, -5.07, 
    0.51, -2.28, 8.89, -7.86, -10.65, -7.86, -7.86, -7.86, -7.86, 
    -5.07, -3.65, -1.29, 2.96, 4.15, 6.92, -2.08, 1.05, -5.51, -0.48, 
    -2.95, 4.24, -6.34, -8.73, -6.97, -1.62, -9.22, -11.66, -7.73, 
    4.7, 4.7, 6.1, 8.89, 7.49, 8.89, 6.1, 0.51, 8.89, 6.1, 8.89, 
    3.31, -2.28, -2.28, -2.28, -2.28, -2.28, -5.07, -29.5, -19.03, 
    -10.65, -16.24, -14.84, -27.41, -16.24, -32.99, -24.61, -44.16, 
    -35.78, -58.12, -52.54, -55.33, -49.74, -49.74, -55.33, -72.08, 
    -16.94, -9.26, -5.07, -10.65, -7.86, -16.24, -9.26, -19.03, -16.24, 
    -24.61, -30.2, -35.78, -24.61, -30.2, -38.57, -27.41, -38.57, 
    -58.12, -21, -11.72, -6.77, -12.43, -10.48, -18.3, -11.61, -22.85, 
    -18.07, -27.5, -26.07, -36.69, -32.35, -33.93, -35.27, -30.9, 
    -35.64, -42.99), index = structure(c(1513292400, 1516316400, 
    1518735600, 1521154800, 1524175200, 1529013600, 1537480800, 1545346800, 
    1561068000, 1576796400, 1592517600, 1608246000, 1639695600, 1671145200, 
    1702594800, 1734649200, 1766098800, 1797548400), tzone = "", tclass = c("POSIXct", 
    "POSIXt")), .indexCLASS = c("POSIXct", "POSIXt"), .indexTZ = "", tclass = c("POSIXct", 
    "POSIXt"), tzone = "", .Dim = c(18L, 6L), .Dimnames = list(NULL, 
        c("Call Median", "Call Mean", "Call 3rd Qu.", "Put 1st Qu.", 
        "Put Median", "Put Mean")), class = c("xts", "zoo"))
    

    因此,我想将我的数据分组如下:

    • 通过 as.character(index(distance)) 喜欢 ggplot2::diamonds$cut 在x轴上;
    • 根据需要使用不同的颜色 colnames(distance) 喜欢 ggplot2::diamonds$clarity ;

    到目前为止,我的审判:

    # Transpose is just because... who knows? Maybe it works
    distance.t = t(distance)
    
    as.data.frame(distance.t) %>%
      plot_ly(
        x = ~rownames(distance.t),
        y = ~as.data.frame(distance.t),
        type = "bar",
        color = ~colnames(distance.t))
    

    结果:

    Error: Column `color` must be length 1 or 18, not 6
    

    我错过了什么?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Maximilian Peters    6 年前

    Plotly期望 x y 值具有相同的形状或长度为1,即它们都具有相同的坐标。

    在文档中的示例中,每个值都有自己的值 x , y color 价值您的数据包含相同的信息,但不是以绘图可以理解的方式。

    您可以通过迭代数据并按顺序添加条来绘制数据。

    p <- plot_ly(x = attr(distance, "index"))
    for (i in 1:dim(distance)[2])
    {
      p <- add_bars(p,
                    y = as.numeric(distance[,i]),
                    name = colnames(distance)[i]
                    )
    }
    

    enter image description here