[英]How to overlay 3 functions on one plot using R
我有三個功能和一個 plot 代碼:
f1 <- function(c){0.187*c-0.000236*c^2+0.194*10-0.00330*100-0.000406*10}
f2 <- function(c){0.187*c-0.000236*c^2+0.194*16.53-0.00330*(16.53^2)-0.000406*16.53}
f3 <- function(c){0.187*c-0.000236*c^2+0.194*20-0.00330*400-0.000406*20}
我希望 plot 所有這三個都在同一張圖上。 我目前有:
png("figure.png")
plot(f1(1:1000), type="l", xlab="x", ylab="y", main="the plot :)")
plot(f2(1:1000), type="l", xlab="x", ylab="y", add = T)
dev.off()
到目前為止,這僅在 plot 上產生f1而不是f1和f2 。 我相信我采取了錯誤的方法,因為我正在生產另一個 plot並試圖將其添加到預先存在的 plot 中。 我不確定是否使用 geom_line 或類似的東西,只是覆蓋它。
plot 多個功能是否有直接的方法並將它們覆蓋在同一個 plot 中?
geom_line
用於ggplot2
,這是一個完全不同的繪圖系統。
如果你從plot()
開始,你可以使用lines()
在你當前的 plot 上畫線。 您的線條非常接近,因此在這里並不重要,但是對於基本plot
,您通常需要提前計算最大范圍,以便您可以設置您的 plot Z05B8C74CBD96FBF2DE4C1A352702FFF4:
x = 1:1000
y1 = f1(x)
y2 = f2(x)
y3 = f3(x)
y_range = range(c(y1, y2, y3))
plot(x, y1, ylim = y_range, type="l", xlab="x", ylab="y", main="the plot :)", col = "red")
lines(x, y2, col = "blue")
lines(x, y3, col = "chartreuse")
ggplot2
用於處理數據幀中的數據 - 特別是長格式數據幀。 以下是我們如何使用ggplot
解決問題。 (注意,與上面不同, ggplot
計算 plot 限制並自動給出一個漂亮的圖例。)
library(ggplot2)
dd = data.frame(x, y1, y2, y3)
d_long = reshape2::melt(data = dd, id.vars = "x", variable.name = "fun", value.name = "y")
ggplot(d_long, aes(x = x, y = y, color = fun)) +
geom_line()
或者堅持使用基本 R 像您的代碼一樣繪圖,您可以使用lines
添加額外的功能
plot(f1(1:1000), type="l", xlab="x", ylab="y", main="the plot :)")
lines(1:1000, f2(1:1000))
lines(1:1000, f3(1:1000))
如果您想要兩個緊挨着另一個的圖,則必須設置調色板的參數。 在 png() 命令之后使用 par(mfrow=c(1,2))。
png("figure.png")
par(mfrow=c(1,2))
plot(f1(1:1000), type="l", xlab="x", ylab="y", main="the plot :)")
plot(f2(1:1000), type="l", xlab="x", ylab="y", add = T)
dev.off()
對於函數,您還可以使用curve
:
f1 <- function(c){0.187*c-0.000236*c^2+0.194*10-0.00330*100-0.000406*10}
f2 <- function(c){0.187*c-0.000236*c^2+0.194*16.53-0.00330*(16.53^2)-0.000406*16.53}
f3 <- function(c){0.187*c-0.000236*c^2+0.194*20-0.00330*400-0.000406*20}
c0 <- 1
c <- 1000
curve(f1, c0, c, main = 'the plot :)', xlab = 'x', ylab = 'y')
curve(f2, c0, c, add = T)
curve(f3, c0, c, add = T)
正如@Gregor 所說, geom_line()
是一個ggplot()
調用。 將 go 全部放入tidyverse
中,可以這樣做:
#or with ggplot / geom_line
library(tidyverse)
map_df(list(f1 =f1,f2 = f2,f3 = f3), exec, 1:1000)%>%
mutate(x = 1:1000)%>%
gather(key = fx,value = value, -x)%>%
ggplot(aes(x = x, y = value, col = fx)) + geom_line()
最后,您可能也對facet_grid
感興趣:
map_df(list(f1 =f1,f2 = f2,f3 = f3), exec, 1:1000)%>%
mutate(x = 1:1000)%>%
gather(key = fx,value = value, -x)%>%
ggplot(aes(x = x, y = value)) + geom_line() +
facet_grid(rows = vars(fx))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.