简体   繁体   中英

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:

在此处输入图片说明

Can anybody help me?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM