我正在尝试从同一图表上的数据集中绘制3行,并使用ggplot2显示它们.我想手动设置每行的颜色和形状.
问题是颜色/形状是根据标签的词典顺序设置的,我似乎对所选择的内容没有任何控制.
这就是我尝试过的:
px <-
ggplot(dataset) +
stat_smooth(aes(x=id, y=dataset[,4], colour="2000", linetype="2000"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
stat_smooth(aes(x=id, y=dataset[,3], colour="500", linetype="500"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
stat_smooth(aes(x=id, y=dataset[,2], colour="1000", linetype="1000"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
theme(legend.title=element_blank()) +
xlab("x") +
ylab("y") +
ggtitle("px")
py <-
ggplot(dataset) +
stat_smooth(aes(x=id, y=dataset[,4], colour="1000", linetype="1000"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
stat_smooth(aes(x=id, y=dataset[,3], colour="500", linetype="500"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
stat_smooth(aes(x=id, y=dataset[,2], colour="2000", linetype="2000"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
theme(legend.title=element_blank()) +
xlab("x") +
ylab("y") +
ggtitle("py")
pz <-
ggplot(dataset) +
stat_smooth(aes(x=id, y=dataset[,4], colour="B1000", linetype="B1000"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
stat_smooth(aes(x=id, y=dataset[,3], colour="C500", linetype="C500"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
stat_smooth(aes(x=id, y=dataset[,2], colour="A2000", linetype="A2000"),se=FALSE, size=1, span=0.1, level=0.90, method="loess") +
theme(legend.title=element_blank()) +
ylab("y") +
xlab("x") +
ggtitle("pz")
Run Code Online (Sandbox Code Playgroud)
这就是我得到的:

我的数据如下:
> head(dataset)
id A B C
1 1 0 26 44
2 2 0 0 0
3 3 0 0 46
4 4 26 22 0
5 5 16 0 0
6 6 0 0 30
Run Code Online (Sandbox Code Playgroud)
我希望有一些像最后一样的东西,在图例框上有这些确切的颜色,形状和排序,但不必在每个标签前放置ABC.
我怎样才能做到这一点?
PS:即使我使用stat_smooth,geom_line也是如此
你的问题是因为这不是ggplot2中的事情.如果你曾经[在里面使用过aes(),这肯定表明你做错了.
geom我们融合数据框,然后将变量映射到美学,而不是对单个单独调用.
dat <- read.table(text = " id A B C
1 1 0 26 44
2 2 0 0 0
3 3 0 0 46
4 4 26 22 0
5 5 16 0 0
6 6 0 0 30",header = TRUE,sep = "")
require(reshape2)
datm <- melt(dat,id.vars = 'id')
datm$variable <- factor(datm$variable,levels = c('C','A','B'))
ggplot(datm) +
geom_line(aes(x = id,y = value,colour = variable,linetype = variable))
Run Code Online (Sandbox Code Playgroud)
我在geom_line这里使用过,因为你的样本数据太小而无法使用geom_smooth,但它的工作方式相同.一旦融化了数据,就可以通过调整因子级别的顺序来控制顺序.
你可以随时更改的水平比其他的东西A通过C的过程.