Reputation: 539
I'm looking to create a plotly chart where the colors of each slice another variable in the dataframe. This is pretty simple to do in ggplot2, however, I'm struggling to convert this to plotly.
My sample code is here:
Product <- c("Product1","Product2","Product3","Product4","Product5","Product6","Product7")
Value <- c(1000000,200002,599996,1399994,2199992,2999990,3799988)
Rating = c(0.24, 0.28, 0.17, 0.1, 0.5, 0.6, 0.34)
df <- data.frame(Product,Value, Rating)
plot_ly(df, labels = ~Product, values = ~Value, type = 'pie', textinfo = 'label+percent',
marker = list(color = ~Rating)) %>%
layout(xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
It seems like I am not doing something right with the "color" attribute. I would like for there to be a continuous scale color scheme, preferably a red color when the Rating variable is near 0 and green when it is near 1.
Thanks.
Upvotes: 2
Views: 2691
Reputation: 31689
You could
sort your dataframe
sorted_df <- df[order(df$Rating),]
add custom colors using colorRampPalette
gradient <- colorRampPalette(c('red', 'green'))
sorted_df$colors <- gradient(dim(df)[1])[as.numeric(cut(sorted_df$Rating,
breaks = dim(df)[1]))]
assign the colors to your plot
marker = list(colors = ~colors)
The color scale could use some tweaking.
Product <- c("Product1","Product2","Product3","Product4","Product5","Product6","Product7")
Value <- c(1000000,200002,599996,1399994,2199992,2999990,3799988)
Rating = c(0.24, 0.28, 0.17, 0.1, 0.5, 0.6, 0.34)
df <- data.frame(Product,Value, Rating)
sorted_df <- df[order(df$Rating),]
gradient <- colorRampPalette(c('red', 'green'))
sorted_df$colors <- gradient(dim(df)[1])[as.numeric(cut(sorted_df$Rating,
breaks = dim(df)[1]))]
plot_ly(sorted_df, labels = ~Product, values = ~Value, type = 'pie', textinfo = 'label+percent',
marker = list(colors = ~colors)) %>%
layout(xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))
Upvotes: 4