首页 > 解决方案 > 如何绘制用一种缩放颜色着色并使用 plotly 包的饼图

问题描述

我有这个示例数据框:

> Data
                    Produits Pourcentages
1              Crème de jour        27.10
2                      sérum        14.50
3              Crème de nuit        13.80
4                     masque         8.82
5      démaquillant à rincer         7.73
6  démaquillant sans rincage         7.24
7                     lotion         6.57
8                eau florale         5.83
9                      huile         5.65
10          produits teintés         2.82

然后,我想仅使用包绘制饼图plotly

library(dplyr)
library(plotly)

p <- plot_ly(Data, labels = ~Produits, values = ~Pourcentages, type = 'pie') %>%
  layout(title = 'United States Personal Expenditures by Categories in 1960',
         xaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE),
         yaxis = list(showgrid = FALSE, zeroline = FALSE, showticklabels = FALSE))

它给了我这个饼图:

在此处输入图像描述

但我不需要得到很多颜色,我只需要一种缩放颜色,它的强度随着变量的函数增加 Pourcentages

换句话说,我想要一个使用plotly这样的包的饼图:

在此处输入图像描述

谢谢您的帮助 !

标签: r

解决方案


这是从这里扩展答案的另一个解决方案:

Data <- data.frame(
  Produits = c("Crème de jour", "sérum", "Crème de nuit", "masque", "démaquillant à rincer", "démaquillant sans rincage", "lotion", "eau florale", "huile", "produits teintés"),
  Pourcentages = c(27.10, 14.50, 13.80, 8.82, 7.73, 7.24, 6.57, 5.83, 5.65, 2.82)
)
gradient <- colorRampPalette(c('lightblue', 'darkblue'))
Data$colors <- gradient(dim(Data)[1])[as.numeric(cut(Data$Pourcentages, breaks = dim(Data)[1]))]
plot_ly(Data, labels = ~Produits, values = ~Pourcentages, type = 'pie', marker = list(colors = ~colors))

在此处输入图像描述


推荐阅读