简体   繁体   中英

plotly bar chart with number of colors = number of categories

For the following object:

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")

I'm looking to create a plotly bar chart while specifying a color for each bar. Unfortunately, it will only take n-1 colors, creating its own "gradient" for the remaining color.

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

if I try to add an 8th color...

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

now all of the bars are yellow.

Use the color argument to marker argument instead.

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"))) 

as alternative you can also produce a plot in plotly with ggplot2, which would give you what you want.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM