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

时间:2017-11-22 16:21:13

标签: r bar-chart plotly

我正在尝试使用我的数据集重现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"))

所以我想像这样分组我的数据:

  • by as.character(index(distance)),如x轴上的ggplot2::diamonds$cut;
  • 根据colnames(distance) {/ 1}}使用不同的颜色,如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 个答案:

答案 0 :(得分:1)

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

在文档的示例中,每个值都有自己的xycolor值。您的数据保存的信息相同,但Plotly无法理解。

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

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