以下面的例子为例:
library(ggplot2)
dsamp <- diamonds[sample(nrow(diamonds), 1000), ]
ggplot(dsamp, aes(x = x)) +
geom_line(aes(y = y, linetype = "Simple Model")) +
geom_line(aes(y = z, linetype = "Complex Model"))
Run Code Online (Sandbox Code Playgroud)
好的。我的问题是我想要反转线型。我希望简单模型有实线,复杂模型有虚线。默认情况下,字母顺序似乎决定了这里的线型。我已经使用 scale_linetype_manual 等尝试了不同的变体,但尽我所能,我无法将简单的线条设为实线,将复杂的线条设为虚线,同时在图例中保留“简单”和“复杂”标题。在有人提出建议之前,我试图避免融化/重塑这些数据,使两个 y 变量都在 1 列中,因为实际数据在绘图等中具有更多内容,并且会非常复杂。
编辑:好的,感谢 Haboryme 的回复。我找到了我困惑的根源。
采取以下情节:
ggplot(dsamp, aes(x = x)) +
geom_line(aes(y = y, linetype = "Simple Model"), size = 1.5) +
geom_line(aes(y = z, linetype = "Complex Model"), size = 1.5) +
scale_linetype_manual(values=c( 5, 1))
Run Code Online (Sandbox Code Playgroud)
但是,如果我将其更改为线型 3:
ggplot(dsamp, aes(x = x)) +
geom_line(aes(y = y, linetype = "Simple Model"), size = 1.5) +
geom_line(aes(y = z, linetype = "Complex Model"), size = 1.5) +
scale_linetype_manual(values = c( 3, 1))
Run Code Online (Sandbox Code Playgroud)
好吧,我想这解决了我的问题 - 我只需要使用线型 3。看起来线型 5 的尺寸为 1.5 不太适合图例空间?
ggplot(dsamp, aes(x=x)) +
geom_line(aes(y=y, linetype="Simple Model"),size=1.5) +
geom_line(aes(y=z, linetype="Complex Model"),size=1.5)+
scale_linetype_manual(values=c(5,1))
Run Code Online (Sandbox Code Playgroud)
上面的代码将为您提供一个图,其中两条线在图例中看起来相似。
这是因为linetype=5相当于“longdash”(2 是“dashed”)。长破折号太长而无法在图例中显示。
如果您想size=1.5使用长破折号保留(或更高)并拥有适当的图例,您还需要更改图例的大小,例如:
+theme(legend.key.size=unit(2,"cm"))
Run Code Online (Sandbox Code Playgroud)