Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adjusting the width of legend for continuous variable

Tags:

r

legend

ggplot2

I have a script below to illustrate my question:

temp.df <- data.frame(x=1:100,y=1:100,z=1:100,stringsAsFactors=FALSE)
chart <- ggplot(data=temp.df,aes(x=x,y=y))
chart <- chart + geom_line(aes(colour=z))
chart <- chart + scale_colour_continuous(low="blue",high="red")
chart <- chart + theme(legend.position="bottom")
# so far so good, but I think the legend positioned at bottom with such a small size is a waste of space, so I want to "widen" it using the line below...
chart <- chart + guides(colour=guide_legend(keywidth=5,label.position="bottom"))
# oops, it changed to legend for categorical variable

How can I widen the "continuous variable" legend positioned at bottom?

like image 651
lokheart Avatar asked Feb 01 '13 16:02

lokheart


People also ask

How do I change the size of a legend key in R?

To change the Size of Legend, we have to add guides() and guide_legend() functions to the geom_point() function. Inside guides() function, we take parameter color, which calls guide_legend() guide function as value.

How do I change the legend position in R?

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 . To put it inside the plot area, specify a vector of length 2, both values going between 0 and 1 and giving the x and y coordinates.

How do I change the legend label in ggplot2?

You can use the following syntax to change the legend labels in ggplot2: p + scale_fill_discrete(labels=c('label1', 'label2', 'label3', ...))


2 Answers

Instead of function guides() you should use the function theme() and set the legend.key.width=

temp.df <- data.frame(x=1:100,y=1:100,z=1:100,stringsAsFactors=FALSE)
chart <- ggplot(data=temp.df,aes(x=x,y=y))
chart <- chart + geom_line(aes(colour=z))
chart <- chart + scale_colour_continuous(low="blue",high="red")
chart <- chart + theme(legend.position="bottom")
chart <- chart + theme(legend.key.width=unit(3,"cm"))
like image 56
Didzis Elferts Avatar answered Oct 12 '22 02:10

Didzis Elferts


You can use guide_colourbar instead of guide_legend in your code :

temp.df <- data.frame(x=1:100,y=1:100,z=1:100,stringsAsFactors=FALSE)
chart <- ggplot(data=temp.df,aes(x=x,y=y))
chart <- chart + geom_line(aes(colour=z))
chart <- chart + scale_colour_continuous(low="blue",high="red")
chart <- chart + theme(legend.position="bottom")
chart + guides(colour=guide_colourbar(barwidth=30,label.position="bottom"))

enter image description here

like image 31
juba Avatar answered Oct 12 '22 02:10

juba