Programing

개체에 플롯 저장

lottogame 2020. 11. 15. 10:49
반응형

개체에 플롯 저장


에서는 ggplot2그래픽을 R 객체에 쉽게 저장할 수 있습니다.

p = ggplot(...) + geom_point()      # does not display the graph
p                                   # displays the graph

표준 함수 plot는 그래픽을 void 함수로 생성하고 NULL을 반환합니다.

p = plot(1:10)     # displays the graph
p                  # NULL

plot에서 만든 그래픽을 개체에 저장할 수 있습니까?


기본 그래픽은 장치에서 직접 그립니다.

당신은 사용할 수 있습니다

1- recordPlot

2- 최근에 도입 된 gridGraphics패키지 , 기본 그래픽을 해당 그리드로 변환

여기에 최소한의 예가 있습니다.

plot(1:10) 

p <- recordPlot()
plot.new() ## clean up device
p # redraw

## grab the scene as a grid object
library(gridGraphics)
library(grid)
grid.echo()
a <- grid.grab()

## draw it, changes optional
grid.newpage()
a <- editGrob(a, vp=viewport(width=unit(2,"in")), gp=gpar(fontsize=10))
grid.draw(a)

나는 이것에 너무 늦었지만 내가 질문을 검색했을 때 나타난 첫 번째 질문이었습니다. 그래서 질문을 접하게 될 미래의 시청자를 위해 제 솔루션을 추가하고 싶습니다.

나는 객체 대신 함수를 사용하여 이것을 해결했습니다. 예를 들어, 다른 모수를 가진 두 개의 베타 분포를 비교한다고 가정합니다. 다음을 실행할 수 있습니다.

z1<-rbeta(10000,5,5)
z2<-rbeta(10000,20,20)
plotit<-function(vector,alpha,beta){
plot(density(vector),xlim=c(0,1))
abline(v=alpha/(alpha+beta),lty="longdash")
}

그리고 플롯을 객체가 아닌 함수 로 저장하십시오 .

z.plot1<-function(){plotit(z1,5,5)}
z.plot2<-function(){plotit(z2,20,20)}

다음으로 두 개의 플롯을 객체가 아닌 함수로 호출하여 원하는대로 각 플롯을 호출 할 수 있습니다.

z.plot1()

첫 번째 플롯을 플롯하고

z.plot2()

두 번째를 플롯합니다.

나중에 이것을 우연히 발견하는 사람에게 도움이되기를 바랍니다!


pryr생성 된 개체의 값을 직접 변경하지 않으려면 패키지 의 활성 바인딩 기능을 사용할 수 있습니다 .

library(pryr)
a %<a-% plot(1:10,1:10)

Each time you type a on the console the graph will be reprinted on the screen. The %<a-% operator will rerun the script every time (in case of one graph this is not a problem I think). So essentially every time you use a the code will be rerun resulting in your graph which of course you can manipulate (overlay another plot on top) or save using png for example. No value itself will be stored in a however. The value will still be NULL.

I don't know if the above is what you are looking for but it might be an acceptable solution.


library(ggplot2)
# if mygraph is a plot object
ggsave("myplot1.png",mygraph)

# if the plot is in a list (e.g. created by the Bibliometrics package)
ggsave("myplot1.png",mygraphs[[1]])

참고URL : https://stackoverflow.com/questions/29583849/save-a-plot-in-an-object

반응형