1
votes

I am new to plotly but I am trying to create a clustered column bar chart, that looks something like this, where I can hover over and see the values:

enter image description here

To make this in plotly, here is what I have so far, but I'm not sure how to proceed in order to get the desired output shown above (which is just made from base barplot):

A <- c(.32, 1.89, 12.9, 51.85, 29.96)
B <- c(1.06, 2.65, 21.27, 47.34, 27.65)
C <- c(.96, 3.85, 18.32, 51.44, 25.401)

matrixValueData <- as.data.frame(rbind(A, B, C))

plotly::plot_ly(matrixValueData, x = colnames(matrixValueData), y = A, type = 'bar')

Any help appreciated! Thanks!

1

1 Answers

2
votes

Here's a start:

First, create a vector of ordered factors for Rating:

Rating <- c("Very Poor Value", "Poor Value", "Neutral", "Good Value", "Very Good Value")
Rating <- factor(Rating, levels = Rating, ordered = T)

Then, create the data.frame and reshape it into a long format:

matrixValueData <- data.frame(A, B, C, Rating) %>% 
                       tidyr::gather(Group, Score, -Rating)

    print(head(matrixValueData))
#            Rating Group Score
# 1 Very Poor Value     A  0.32
# 2      Poor Value     A  1.89
# 3         Neutral     A 12.90
# 4      Good Value     A 51.85
# 5 Very Good Value     A 29.96
# 6 Very Poor Value     B  1.06

Finally, plot:

plot_ly(matrixValueData, 
        x = ~Rating, 
        y = ~Score, 
        color = ~Group, 
        type = "bar", 
        marker = list(line = list(color = "black", width = 1)))

plotly_output

You can further manipulate the bar colors and hover text with the marker and text arguments, respectively. More detail in the documentation.