使用不同的线型和标记绘制ggplot折线图

14

我正在尝试在ggplot2中创建一条折线图,其中某些变量使用不同的线型,另一些变量使用不同的标记。

示例1:每个变量使用不同的线型绘制;示例2:每个变量使用不同的标记绘制;示例3:每个变量使用不同的线型和标记绘制。

我希望将X2和X3绘制成不同的线型(实线、虚线),然后将X4和X5绘制成实线,并使用不同的标记(圆形、正方形等等)。

是否有任何方法可以做到这一点?

library(ggplot2)
library(reshape2)

set.seed <- 1
df <- data.frame(cbind(seq(1,10,1),matrix(rnorm(100,1,20), 10, 4)))
d <- melt(df, id="X1")

# Example 1: different line styles
ggplot(d, aes(x=X1, y=value, color=variable)) + 
  geom_line(aes(linetype=variable), size=1)

# Example 2: different markers for each line
ggplot(d, aes(x=X1, y=value, color=variable)) + 
  geom_line() + geom_point(aes(shape=variable, size=4))

# Example 3: differnt line styles & different markers (You see this graph below)
ggplot(d, aes(x=X1, y=value, color=variable)) + 
  geom_line(aes(linetype=variable), size=1) +
  geom_point(aes(shape=variable, size=4))

输入图片说明


2
作为第一个问题,这篇文章写得很好,提供了可重现的示例。干得好! :) - jazzurro
1个回答

13

这里有一个方法。您可以使用两个额外的函数来控制形状和线条类型。 scale_linetype_manual 允许您手动分配线条类型。同样,scale_shape_manual 允许您手动分配任何您想要的形状。

# Example 3: differnt line styles & different markers
ggplot(d, aes(x=X1, y=value, color=variable)) + 
geom_line(aes(linetype=variable), size=1) +
geom_point(aes(shape=variable, size=4)) +
scale_linetype_manual(values = c(1,2,1,1)) +
scale_shape_manual(values=c(0,1,2,3))

在此输入图片描述


太棒了!非常感谢你的帮助。我显然还在学习ggplot2的所有功能。 - learnmorer
@learnmorer 非常愉快。 :) 我每天都在学习ggplot2! - jazzurro
3
我认为geom_point这一行存在错误。大小应该放在括号外面:geom_point(aes(shape=variable), size=4) - luchonacho
@luchonacho 提供的更正还删除了图例中的黑点“4”。 - Kevin Lee

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接