rr-base-graphics

R: default palette used for pie charts


I would like to add a legend to a pie chart in R The default color palette is fine for me, but how can I use it in the legend (to match the colors of the plot)?

pie(table(iris$Species))
legend('right',c('A','B','C'), fill = colors(3))

(I know that I could create a vector of colors to use in the chart in the legend in advance like in my_colors <- colors(3), but this would then not be the default colors. The official documentation only says that the pie() function uses "pastel" colors if the col argument is omitted, but doesn't specify the exact values.)


Solution

  • If you look at the body of the pie function, you will see that the colors are hard-coded into it in the following lines:

       if (is.null(col)) 
            col <- if (is.null(density)) 
                c("white", "lightblue", "mistyrose", 
                    "lightcyan", "lavender", "cornsilk")
            else par("fg")
    

    So, you can use the same colors yourself in the call to legend

    pie(table(iris$Species))
    legend('right', c('A','B','C'), fill =  c("white", "lightblue", "mistyrose"))
    

    enter image description here