为什么ggplot在这个多行图中从离散图例切换到连续图例?

时间:2016-07-06 12:46:28

标签: r plot ggplot2

示例df:

 xnom <- seq(0,80,by=20)
 x1 <- xnom+rnorm(5,0,2)
 x2 <- x1*.9
 x3 <- x2*.9
 S1 <- seq(0,1,by=.25)
 S2 <- S1*1.3
 S3 <- S2*1.3
 df <- data.frame(xnom,x1,x2,x3,S1,S2,S3)

我想制作两个不同的情节。每个响应S1, S2, S3针对预测变量xnom绘制,另一个针对相应预测变量Si绘制每个响应xi。在这两种情况下,我想为每个响应创建一条不同颜色的线,并且图例必须总结三个响应的颜色。为此,我写了以下函数:

makeplot <- function(df,xvec){
    library(ggplot2)
if (length(xvec)==1) {
p <- ggplot(data=df, aes_string(x = xvec))
p <- p + geom_line(aes(y = S1, color = "1")) +
geom_point(aes(y = S1, color = "1")) +
geom_line(aes(y = S2, color = "2")) +
geom_point(aes(y = S2, color = "2")) +
geom_line(aes(y = S3, color = "3")) +
geom_point(aes(y = S3, color = "3"))
} else {
p <- ggplot(data=df)
p <- p + geom_line(aes_string(x = xvec[1], y = "S1", color = "1")) +
geom_point(aes_string(x = xvec[1],  y = "S1", color = "1")) +
geom_line(aes_string(x = xvec[2], y = "S2", color = "2")) +
geom_point(aes_string(x = xvec[2], y = "S2", color = "2")) +
geom_line(aes_string(x = xvec[3], y = "S3", color = "3")) +
geom_point(aes_string(x = xvec[3] , y = "S3", color = "3"))
}
p <- p + labs(color = "Section")
print(p)
}

在单一预测案例中,它运作良好:

 makeplot(df,"x1")

enter image description here

ggplot制作一个看起来很棒的离散比例图例。但是,当我将每个响应与相应的预测变量匹配时,由于某种原因,ggplot会切换到连续的比例:

makeplot(df,c("x1","x2","x3"))

enter image description here

这看起来很难看:在我的案例中,第2.5节毫无意义。为什么会这样,我怎么能避免呢?我担心它可能与aes_string有关。但是,我需要一些方法来管理我的函数中的变量预测变量名称,因为所有这些都是更大的代码的一部分,其中预测变量名称可以在运行时更改。

1 个答案:

答案 0 :(得分:0)

要正式确定@RichardTelford和@DeltaIV提出的建议,是否有理由不能使用以下内容?

请注意,双melt不太理想(我知道有更好的方法,但我现在正在对它进行消隐)并且我在标签中编码,而不是使用{{1} },xlab,并设置密钥的名称等。

ylab

enter image description here

library(ggplot2)
library(dplyr)
library(reshape2)

melt(df, id.vars = c("xnom")
     , measure.vars = paste0("S",1:3)
     , variable.name = "Section"
     , value.name = "Response") %>%
  mutate(Section = gsub("^S","",Section)) %>%
  ggplot(aes(x = xnom
             , y = Response
             , col = Section)) +
  geom_point() +
  geom_line()

enter image description here