[问题] ggplot2 画function

楼主: Itok (浪里白条)   2018-04-16 22:04:27
[问题类型]:
程式咨询(我想用R 做某件事情,但是我不知道要怎么用R 写出来)
[软件熟悉度]:
使用者(已经有用R 做过不少作品)
[问题叙述]:
我有用ggplot2画function,想画多条线在同一张图,
用for 循环却只能画出最后一条,
想请教版上高手如何处理,谢谢。
[程式范例]:
library(ggplot2)
ap<-c(10,20,30,40,50,60,70,80,90,100,150,200,250,300,350,400,450,500,550,600,650,700,750,800,850,900,950,1000)
#initial plot p
p<-ggplot(data.frame(x=c(0,200)), aes(x))+ylim(0,200)
#画出多条function
myPlot<-ggplot(data.frame(x=c(0,200)), aes(x))+ylim(0,200)+
stat_function(fun=function(x)2/(ap[1])*x^2, geom="line", aes(colour="010"))+
stat_function(fun=function(x)2/(ap[2])*x^2, geom="line", aes(colour="020"))+
stat_function(fun=function(x)2/(ap[3])*x^2, geom="line", aes(colour="030"))+
stat_function(fun=function(x)2/(ap[4])*x^2, geom="line", aes(colour="040"))+
stat_function(fun=function(x)2/(ap[5])*x^2, geom="line", aes(colour="050"))+
stat_function(fun=function(x)2/(ap[6])*x^2, geom="line", aes(colour="060"))+
stat_function(fun=function(x)2/(ap[7])*x^2, geom="line", aes(colour="070"))+
stat_function(fun=function(x)2/(ap[8])*x^2, geom="line", aes(colour="080"))+
stat_function(fun=function(x)2/(ap[9])*x^2, geom="line", aes(colour="090"))+
stat_function(fun=function(x)2/(ap[10])*x^2, geom="line", aes(colour="100"))+
stat_function(fun=function(x)2/(ap[11])*x^2, geom="line", aes(colour="150"))+
stat_function(fun=function(x)2/(ap[12])*x^2, geom="line", aes(colour="200"))+
stat_function(fun=function(x)2/(ap[13])*x^2, geom="line", aes(colour="250"))+
stat_function(fun=function(x)2/(ap[14])*x^2, geom="line", aes(colour="300"))+
stat_function(fun=function(x)2/(ap[15])*x^2, geom="line", aes(colour="350"))+
stat_function(fun=function(x)2/(ap[16])*x^2, geom="line",aes(colour="400"))+
stat_function(fun=function(x)2/(ap[17])*x^2, geom="line",aes(colour="450"))+
stat_function(fun=function(x)2/(ap[18])*x^2, geom="line",aes(colour="500"))
myPlot
#用for循环画仅能画出最后一条
for (i in c(1:18))
{
p<-p+stat_function(fun=function(x){2/(ap[i])*x^2}, geom="line", aes(colour=ap[i]))
}
p
请提供 sessionInfo() 的输出结果,
里面含有所有你使用的作业系统、R 的版本和套件版本资讯,
让版友更容易找出错误
R version 3.3.3 (2017-03-06)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows >= 8 x64 (build 9200)
[关键字]:
ggplot2 function
作者: andrew43 (讨厌有好心推文后删文者)   2018-04-16 22:18:00
按ggplot设计的风格,你应该要先创造一个dataframe包括了所有2 / (ap[k]) * x ^ 2结果以及多一个字段来说明k各别是多少... 所以会有三个字段: x, fun(x), k我上面的k是指ap中各元素之后,就只要一行geom_line()并指定k为不同颜色即可我回个文好了

Links booklink

Contact Us: admin [ a t ] ucptt.com