简体   繁体   中英

Adjust legend width when colour and linetype are scaled manually

Using this data:

http://pastebin.com/pAQePpxr

And this code:

ggplot(data = trial, aes(x = as.factor(Year), y = DV,group = TMT, col = TMT,linetype=TMT))     +
theme_bw() +
geom_point(size = 3,position = pd) +
geom_errorbar(aes(ymin=trial$DV-trial$Error, ymax=trial$DV+trial$Error),
    position = pd, 
    width = 0.1,
    linetype=1) +
geom_line(position = pd) +
ylab("DV") +
xlab("Year") +
theme(axis.title.y=element_text(size=rel(1.1),vjust=0.2),
    axis.title.x=element_text(size=rel(1.1), vjust=0.2),
    axis.text.x=element_text(size=rel(1)),
    axis.text.y=element_text(size=rel(1)), 
    text = element_text(size=13)) +
scale_colour_brewer(palette="Set1") +
scale_colour_manual(name = "Tmt",
                  labels = c("C", "S"),
                  values = c("red","blue"))+scale_linetype_manual(name = "Tmt",
                  labels = c("C", "S"),
                  values = c("solid","dashed"))

I am creating the following graph:

在此输入图像描述

I want to make the linetypes clear in my legend. I'm not sure if my manual scaling of linetype hasn't worked, or whether it is because the width of the legend is too narrow. I have tried adding:

+guides(linetype=guide_legend(keywidth=5))

to adjust the width, but it doesn't work. Any one got any ideas how to resolve this issue?

Many thanks!

To change width of legend keys you should use the function theme() and argument legend.key.width= . You will also need package grid to set units.

library(grid)
+ theme(legend.key.width=unit(1,"cm"))

But in your particular case you need to make another change to your plot. As you are setting linetype=1 in geom_errorbar() both lines in legend will appear as solid. So you need to add argument show_guide=FALSE to geom_errorbar() .

  + geom_errorbar(aes(ymin=DV-Error, ymax=DV+Error),
                width = 0.1,linetype=1,
                   show_guide=FALSE)

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