作者Itok (浪里白条)
看板R_Language
标题[问题] ggplot2 画function
时间Mon Apr 16 22:04:27 2018
[问题类型]:
程式谘询(我想用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
--
※ 发信站: 批踢踢实业坊(ptt.cc), 来自: 125.230.69.206
※ 文章网址: https://webptt.com/cn.aspx?n=bbs/R_Language/M.1523887469.A.3F3.html
1F:→ andrew43: 按ggplot设计的风格,你应该要先创造一个dataframe 04/16 22:18
2F:→ andrew43: 包括了所有2 / (ap[k]) * x ^ 2结果以及多一个栏位来说 04/16 22:19
3F:→ andrew43: 明k各别是多少... 所以会有三个栏位: x, fun(x), k 04/16 22:20
4F:→ andrew43: 我上面的k是指ap中各元素 04/16 22:20
5F:→ andrew43: 之後,就只要一行geom_line()并指定k为不同颜色即可 04/16 22:21
6F:→ andrew43: 我回个文好了 04/16 22:28