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:
(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?
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 .
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.
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.
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="")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With