【问题标题】:plotly bar chart with number of colors = number of categories带有颜色数的绘图条形图 = 类别数
【发布时间】:2016-04-20 06:34:51
【问题描述】:

对于以下对象:

rawData <-
structure(list(obs = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), key = structure(1:8, .Label = c("sadness", 
"neutral", "contempt", "disgust", "anger", "surprise", "fear", 
"happiness"), class = "factor"), value = c(2.36220472440945, 
89.3700787401575, 0.393700787401575, 0.78740157480315, 0, 0.78740157480315, 
0, 6.2992125984252)), .Names = c("obs", "key", "value"), row.names = c(NA, 
8L), class = "data.frame")

我希望在为每个条形指定颜色的同时创建一个绘图条形图。 不幸的是,它只需要 n-1 种颜色,为剩余的颜色创建自己的“渐变”。

rawData %>% 
    group_by(obs) %>%
    plot_ly(x = obs, 
            y = value, 
            type = "bar", 
            color = key,
            colors = c("blue","grey","darkred","green","orange","black","purple"))

如果我尝试添加第 8 种颜色...

rawData %>% 
        group_by(obs) %>%
        plot_ly(x = obs, 
                y = value, 
                type = "bar", 
                color = key,
                colors = c("blue","grey","darkred","green","orange","black","purple","yellow"))

现在所有的条都是黄色的。

【问题讨论】:

    标签: r plotly r-plotly


    【解决方案1】:

    作为替代方案,您还可以使用 ggplot2 生成绘图,这将给您想要的。

    p <- ggplot(data=rawData, aes(x=obs, y=value, color=key, group=key, fill=key)) + geom_bar(stat='identity', position='dodge') + scale_fill_manual(values=c("blue","grey","darkred","green","orange","black","purple","yellow")) + scale_color_manual(values=c("blue","grey","darkred","green","orange","black","purple","yellow"))
    
    ggplotly(p)
    

    【讨论】:

    • 您没有在帖子中提及 ggvis。好久没用ggvis所以不知道,抱歉:-)
    【解决方案2】:

    使用color 参数代替marker 参数。

    rawData %>% 
      group_by(obs) %>%
      plot_ly(x = obs, 
        y = value, 
        type = "bar", 
        color = key,
        marker = list(color=c("blue","grey","darkred","green","orange","black","purple","yellow"))) 
    

    【讨论】:

      猜你喜欢
      • 2016-04-11
      • 2016-03-20
      • 1970-01-01
      • 1970-01-01
      • 2020-04-11
      • 2019-03-07
      • 2019-03-23
      • 2020-12-07
      • 2015-11-07
      相关资源
      最近更新 更多