无法在ggplot2中显示图例

时间:2016-12-13 20:26:36

标签: r ggplot2

我是R(我使用RStudio)和ggplot2的新手。我无法在任何情节上看到一个传奇。我想知道这是否意味着我有一些禁止传说的全局参数集?我已经浏览了这个网站和其他人,并尝试了太多的东西列出,无济于事。这是示例工作代码。我需要一个描述两条线(绿色和红色)的图例。我需要做什么? 谢谢。

ndata <- 100


library(ggplot2)
library(MASS)
require(ggplot2)
require("ggplot2")
require(car)
library(grid)
library(mgcv)
library(Matrix)
require(graphics)
options(error = browser)



legend_test <- function (ndata)  {

  #Generate the predictor values, which are times in the sequence.
  xmin <- -5
  xmax <- 5
  x <- runif(ndata, min = xmin, max = xmax)

  #Sort into increasing order
  x <- sort(x)

  #Define the mean values to lie along a straight line
  int <- 1
  slp <- 1
  st_lne <- as.vector(int + slp*x)

  #Generate normal random deviates as measurements errors
  #along the straight line
  zq <- rnorm(ndata, mean = st_lne, sd = 1)

  #Plot the measurements and the fits
  xq <- data.frame(x, zq)
  ggp <- ggplot(data = xq, aes(x, zq)) + geom_point(shape = 16, size = 2)  

  ggp <- ggp + theme(axis.text.y=element_text(size=25))
  ggp <- ggp + theme(axis.text.x=element_text(size=25))
  ggp <- ggp + theme(axis.title.y=element_text(size=25))
  ggp <- ggp + theme(axis.title.x=element_text(size=25))

  ymin <- int + slp*xmin - 2
  ymax <- int + slp*xmax + 2
  ggp <- ggp + xlab("x") + ylab("y")  + xlim(xmin, xmax) + ylim(ymin, ymax)

  #Add the theoretical line
  x_regress <- as.double(c(xmin, xmax))
  y_int <- as.double(int)
  y_slp <- as.double(slp)
  y_regress <- c(y_int + y_slp*x_regress[1], y_int + y_slp*x_regress[2])
  lmodf <- data.frame(x_regress, y_regress)
  ggp <- ggp + geom_path(data = lmodf, aes(x_regress, y_regress), linetype = 1, size = 0.7, color = "green")

  #Simple Regression fit to straight line

  lmo <- lm(zq ~ x)
  #Add the regression line
  y_int <- as.double(lmo$coefficients[1])
  y_slp <- as.double(lmo$coefficients[2])
  y_regress <- c(y_int + y_slp*x_regress[1], y_int + y_slp*x_regress[2])
  lmodf <- data.frame(x_regress, y_regress)
  ggp <- ggp + geom_path(data = lmodf, aes(x_regress, y_regress), linetype = 2, size = 0.9, color = "red")

    print(ggp)


}

1 个答案:

答案 0 :(得分:0)

试试这个:

#Add the theoretical line
  y_int <- as.double(int)
  y_slp <- as.double(slp)
  lmodf <- data.frame(Guide ='Theory',Slope = y_slp, Intercept = y_int)

  #Simple Regression fit to straight line

  lmo <- lm(zq ~ x)
  #Add the regression line
  y_int <- as.double(lmo$coefficients[1])
  y_slp <- as.double(lmo$coefficients[2])
  lmodf <- rbind(lmodf,data.frame(Guide='Reality',Slope = y_slp, Intercept = y_int))
  ggp <- ggp + 
    geom_abline(data = lmodf, aes(slope = Slope, intercept = Intercept,color =Guide,linetype = Guide), size = 0.9)+
    scale_color_brewer(palette = 'Set1')

    print(ggp)

我尝试尽可能少地修改你的代码以使其工作,所以这有点尴尬,但它会让你走上正确的道路。

另请注意,您可以通过一次调用主题来设置所有轴文本大小值。

ggp <- ggp + theme( axis.text=element_text(size=25), axis.title=element_text(size=25) )

如果您希望axis.text.yy分开调整,则只需使用x