密谋-创建具有连续色标的饼图 [英] Plotly - Create Pie Chart with continuous color scale
问题描述
我正在寻找一个可绘制的图表,其中每个数据的颜色将数据框中的另一个变量切成薄片.这在ggplot2中非常简单,但是,我正在努力将其转换为plotly.
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.
我的示例代码在这里:
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))
这是输出:
似乎我对"color"属性的处理不正确.我希望有一个连续的比例尺配色方案,当Rating变量接近0时最好是红色,而当其接近1时最好是绿色.
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.
谢谢.
推荐答案
您可以
-
对数据框进行排序
sort your dataframe
sorted_df <- df[order(df$Rating),]
使用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))
这篇关于密谋-创建具有连续色标的饼图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!