我是R(我使用RStudio)和ggplot2的新手。我無法在任何情節中顯示圖例。我想知道這是否意味着我有一些全球參數設置,禁止傳說?我已經瀏覽過這個網站和其他人,並嘗試了太多事情列出,無濟於事。這裏是示例工作代碼。我需要一個描述兩條線(綠色和紅色)的圖例。我需要做什麼? 謝謝。不能讓傳說顯示在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)
}
嘗試添加註釋功能。 'ggp + annotate(「text」,x = 4,y = 25,label =「這就是你想要的嗎?」,color ='green')' –