Plotly - 创建具有连续色标的饼图

Plotly - Create Pie Chart with continuous color scale

我想创建一个绘图图表,其中每个切片的颜色与数据框中的另一个变量相关联。这在 ggplot2 中非常简单,但是,我正在努力将其转换为 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 时为绿色。

谢谢。

你可以

  • 对数据框进行排序

    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]))]
    
  • 为您的绘图指定颜色

    marker = list(colors = ~colors)
    

这给了你

色标可以进行一些调整。


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