2
votes

I am creating a simple Plotly bar plot with following data, where the color of the individual Bars will be varying based on the respective values of the Bar. However range of the color should be defined i.e. ranging from Blue (smallest) to Red (highest)

df <- data.frame(x = c('a', 'B'), 
                 y = c(100, 50),
                 z = c(100, 50))


plot_ly(data = df, 
        x = ~x, 
        y = ~y, 
        marker = list(color = ~z), 
        colors = c("blue", "red"), 
        type = "bar")

Unfortunately Plotly displays Bar chart with something different Color-scheme. Could you please point me the right code .

Thanks in advance

1

1 Answers

1
votes

I guess you want something like this:

plot_ly(data = df, 
            x = ~x, 
            y = ~y, 
            marker = list(color =c("blue", "red")), 
            type = "bar")

[EDIT]:

As per the comments I have edited the code. Hope this is what you want.

 df <- data.frame(x = c('a', 'B', "c", "d", "e"), 
                     y = c(100, 50, 20, 10, 100),
                     z = c(100, 50,  20, 10, 100))


    colfunc <- colorRampPalette(c("blue", "red"))
    pal <- colfunc(max(df$z))[df$z]

    plot_ly(data = df, 
            x = ~x, 
            y = ~y, 
            marker = list(color =  pal), 
            type = "bar")