简体   繁体   English

手动缩放颜色和线型时调整图例宽度

[英]Adjust legend width when colour and linetype are scaled manually

Using this data: 使用此数据:

http://pastebin.com/pAQePpxr 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= . 要更改图例键的宽度,您应该使用函数theme()和参数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. 当您在geom_errorbar()中设置geom_errorbar() linetype=1geom_errorbar()两条线都将显示为实线。 So you need to add argument show_guide=FALSE to geom_errorbar() . 因此,您需要将参数show_guide=FALSE添加到geom_errorbar()

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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