How to combine a plot and legend?

18,985

Solution 1

You are off the coordinate system. Try this instead

# Create a legend at the right   
legend("topleft", c("Mon","Tue","Wed","Thu","Fri"), cex=0.8, fill=colors)

which produces the chart below:

pie chart

See the help page for legend for different placement options.

Solution 2

I think the position 1.5, 0.5 puts it off the page. Try

legend("right", c("Mon","Tue","Wed","Thu","Fri"), cex=0.8, fill=colors)

After the pie function it appears with no legend; the legend function adds the legend to the current plot.

PS. You may also consider other types of plots. Pie charts are notorious for being visually misleading.

Share:
18,985
MadSeb
Author by

MadSeb

Updated on June 04, 2022

Comments

  • MadSeb
    MadSeb almost 2 years

    I'm trying to attach a legend to a plot in R. I tried the following code ( taken from http://www.harding.edu/fmccown/r/ )

    # Define cars vector with 5 values
    cars <- c(1, 3, 6, 4, 9)
    
    # Define some colors ideal for black & white print
    colors <- c("white","grey70","grey90","grey50","black")
    
    # Calculate the percentage for each day, rounded to one 
    # decimal place
    car_labels <- round(cars/sum(cars) * 100, 1)
    
    # Concatenate a '%' char after each value
    car_labels <- paste(car_labels, "%", sep="")
    
    # Create a pie chart with defined heading and custom colors
    # and labels
    pie(cars, main="Cars", col=colors, labels=car_labels,
       cex=0.8)
    
    # Create a legend at the right   
    legend(1.5, 0.5, c("Mon","Tue","Wed","Thu","Fri"), cex=0.8, 
       fill=colors)
    

    However, this does not work really well. After the pie(cars, main="Cars", col=colors, labels=car_labels,cex=0.8) line , the plot is shown without a legend :-) .......Every example I see on the Internet seems to have the legend function after the plotting function so it seems very weird..............

    When I try to execute the legend function I get

    legend(1.5, 0.5, c("Mon","Tue","Wed","Thu","Fri"), cex=0.8, + fill=colors) Error in strwidth(legend, units = "user", cex = cex) : plot.new has not been called yet