Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot2: Legend overlapping the plot area - is it possible to manually adjust legend position?

Tags:

r

ggplot2

Lets say I have a dataset about carrot yield from different fields and different breeds:

carrots<-list(Yield=c(345,226,74,559,288,194),
          Field=c("A","B","C","D","E","F"),
          Breed=rep(c("Long","Short"),each=3))
carrots<-data.frame(carrots)

I want to plot a bar plot showing the yield for each field, coloured by breed:

ggplot(carrots,aes(y=Yield,x=Field,fill=Breed)) +
   geom_bar() +
   opts(legend.direction = "horizontal",
        legend.position = "top") +
   labs(fill="")

But the legend is always slightly overlapping the plot area:

plot with slight legend overlap
(source: users.utu.fi)

I've tried manually adjusting the legend position to be outside the plot area, such as with

opts(legend.position=c(0.5,1.1)

but then the plot margins cut off the legend and I'm not sure how I can adjust them. Is there a more subtle solution to this problem?

like image 669
susjoh Avatar asked Jun 29 '11 08:06

susjoh


People also ask

How do I change the position of my legend in R?

position. You can place the legend literally anywhere. To put it around the chart, use the legend. position option and specify top , right , bottom , or left .

How do I change the legend title in ggplot2?

Method 1: Change Legend Title using guides() Function. Now if we want to change Legend Title then we have to add guides and guide_legend functions to the geom_point function. Inside guides() function, we take parameter named 'color' because we use color parameter for legend in ggplot() function.

How do you make a legend outside the plot in R?

In order to draw our legend outside of the plotting area, we can use a combination of the “topright” argument and an additional specification of inset. The “topright” argument specifies that the legend should be in the upper right corner of the graph.


1 Answers

In my environment, the legend does not overlap the plot area at all, but anyway what is overlapping is the background of the legend, so you can remove it by:

ggplot(carrots,aes(y=Yield,x=Field,fill=Breed)) +
 geom_bar() +
 opts(legend.direction = "horizontal",
    legend.position = "top",
        legend.background = theme_blank()) + # this does hack
 labs(fill="")
like image 76
kohske Avatar answered Oct 11 '22 20:10

kohske