Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I make legend next to my piechart in R?

I have made a piechart in R with the next code:

#make slices
slices <- c(19, 26, 55)

# Define some colors 
colors <- c("yellow2","olivedrab3","orangered3")

# Calculate the percentage for each day, rounded to one decimal place
slices_labels <- round(slices/sum(slices) * 100, 1)

# Concatenate a '%' char after each value
slices_labels <- paste(slices_labels, "%", sep="")

# Create a pie chart with defined heading and custom colors and labels
pie(slices, main="Sum", col=colors, labels=slices_labels, cex=0.8)

# Create a legend at the right   
legend("topright", c("DH","UT","AM"), cex=0.7, fill=colors)

But I want the legend next to my piechart. I have also tried the following code: legend("centreright", c("DH","UT","AM"), cex=0.7, fill=colors). But this does not give me a legend next to my pie chart.

Which code do I have to use to make a legend next to my pie chart in the middle?

like image 956
user5543269 Avatar asked May 13 '16 09:05

user5543269


People also ask

How do you show the legend next to a pie chart?

Select a chart and then select the plus sign to the top right. Point to Legend and select the arrow next to it. Choose where you want the legend to appear in your chart.

How do you add a legend to a pie?

MatPlotLib with Python Set the figure size and adjust the padding between and around the subplots. Make a list of labels, colors, and sizes. Use pie() method to get patches and texts with colors and sizes. Place a legend on the plot with patches and labels.

How do I add a title to a pie chart in R?

Pie Chart Title and Colors We will use parameter main to add a title to the chart and another parameter is col which will make use of rainbow colour pallet while drawing the chart. The length of the pallet should be same as the number of values we have for the chart.


1 Answers

You can play with the x and y argument from legend (cf ?legend):

legend(.9, .1, c("DH","UT","AM"), cex = 0.7, fill = colors)

However, a pie chart may not be the best way to represent your data, because our eye is not very good in assessing angles. The only usecase where a pie chart seems reasonable to me is when comparing 2 categories, because due to watches we can assess these proportions rather easily.

enter image description here

like image 172
thothal Avatar answered Oct 12 '22 12:10

thothal