Olympia
Olympia

Reputation: 537

How to adjust the space between 2 columns in a plot legend?

I want to have the plot legend for a pie chart as a single plot (6 graphics at a page - 5 plots, 1 legend). Now I have difficulties adjusting the space between the 2 columns.

I used the following code (by try and error):

 #Colors
 colors=c("blue","green","yellow","orange","red","purple","pink","grey")

 legtext <- c("G","G*E","E","Source","Source*E",
 "Table*E","Table*Block*E","Residual Error") 

 #Code for chart
 pie3D(#data for pie
 rooting1,
 #specify labels vector
 #labels=labels,
 #specify labels size
 labelcex=0.9,
 #how much different pies go from each other
 explode=0.1,
 #height of chart
 height=0.1,
 #Main title
 theta=pi/3,
 #Colors
 col=colors
 )

 #Code for legend
 xcoords <- c(0.9,1,1.1,1.2)
 secondvector <- (1:length(legtext))-1
 textwidths <- xcoords/secondvector # this works for all but the first element
 textwidths[1] <- 0

legend(-1, 0.9,ncol=2,
   c("G","G*E","E","Source","Source*E","Table*E","Table*Block*E","Residual Error"), 
   cex = 0.8, 
   fill = colors,
   text.width=textwidths)

The plot I get is this: I want to remove the vertical lines and if possible, remove the rest of the chart as I only want to display the legend.

Legend I get:

enter image description here

Can anybody help me?

Upvotes: 1

Views: 771

Answers (1)

lebatsnok
lebatsnok

Reputation: 6469

Add bty="n" to your legend:

legend(-1, 0.9,ncol=2,
   c("G","G*E","E","Source","Source*E","Table*E","Table*Block*E","Residual Error"), 
   cex = 0.8, 
   fill = colors,
   text.width=textwidths,
   bty="n")

As for the other question - how to get rid of the chart itself, this will take some fiddling. Basically, what you can do is to make an empty chart, but adjusting the xlim and ylim, as well as margins so that there is enough room for the legend:

par(mar=c(0.1,0.1,0.1,0.1))  # you don't need large margins
# but maybe you need more than 0.1
plot(NA, xlim=c(-1,1), ylim=c(-1,1), axes=FALSE, xlab="", ylab="")
# this makes an empty plot
# you may need to change xlim and ylim (or the x and y of your legend)
# ... so that the legend would start from the left/upper corner

Upvotes: 2

Related Questions