itsource

ggplot2를 사용하여 R에서 투명 배경으로 그래픽을 만드는 방법은 무엇입니까?

mycopycode 2023. 6. 6. 08:19
반응형

ggplot2를 사용하여 R에서 투명 배경으로 그래픽을 만드는 방법은 무엇입니까?

저는 배경이 투명한 R에서 PNG 파일로 ggplot2 그래픽을 출력해야 합니다.기본 R 그래픽에서는 모든 것이 정상이지만 ggplot2에서는 투명도가 없습니다.

d <- rnorm(100) #generating random data

#this returns transparent png
png('tr_tst1.png',width=300,height=300,units="px",bg = "transparent")
boxplot(d)
dev.off()

df <- data.frame(y=d,x=1)
p <- ggplot(df) + stat_boxplot(aes(x = x,y=y)) 
p <- p + opts(
    panel.background = theme_rect(fill = "transparent",colour = NA), # or theme_blank()
    panel.grid.minor = theme_blank(), 
    panel.grid.major = theme_blank()
)
#returns white background
png('tr_tst2.png',width=300,height=300,units="px",bg = "transparent")
p
dev.off()

ggplot2로 투명한 배경을 얻을 수 있는 방법이 있습니까?

초기 그림을 만듭니다.

library(ggplot2)
d <- rnorm(100)
df <- data.frame(
  x = 1,
  y = d,
  group = rep(c("gr1", "gr2"), 50)
)
p <- ggplot(df) + stat_boxplot(
  aes(
    x = x,
    y = y,
    color = group
  ), 
  fill = "transparent" # for the inside of the boxplot
)

완전히 투명한 배경을 갖도록 위의 플롯을 수정하는 가장 빠른 방법은 를 설정하는 것입니다.rect인수, 모든 직사각형 요소가 상속됨rect:

p <- p + theme(rect = element_rect(fill = "transparent"))
          
p

보다 통제된 방법은 설정하는 것입니다.theme()의 보다 구체적인 인수는 개별적으로 다음과 같습니다.

p <- p + theme(
  panel.background = element_rect(fill = "transparent",
                                  colour = NA_character_), # necessary to avoid drawing panel outline
  panel.grid.major = element_blank(), # get rid of major grid
  panel.grid.minor = element_blank(), # get rid of minor grid
  plot.background = element_rect(fill = "transparent",
                                 colour = NA_character_), # necessary to avoid drawing plot outline
  legend.background = element_rect(fill = "transparent"),
  legend.box.background = element_rect(fill = "transparent"),
  legend.key = element_rect(fill = "transparent")
)

p

ggsave() 전용 인수를 제공bg설정하기 위해

배경색.한다면NULL를 사용합니다.plot.background그림 테마의 채우기 값.

ggplot 객체를 작성하는 방법p로.filename투명 배경을 사용하는 디스크:

ggsave(
  plot = p,
  filename = "tr_tst2.png",
  bg = "transparent"
)

또한 다음이 있습니다.plot.background에 추가된panel.background:

df <- data.frame(y=d,x=1)
p <- ggplot(df) + stat_boxplot(aes(x = x,y=y)) 
p <- p + opts(
    panel.background = theme_rect(fill = "transparent",colour = NA), # or theme_blank()
    panel.grid.minor = theme_blank(), 
    panel.grid.major = theme_blank(),
    plot.background = theme_rect(fill = "transparent",colour = NA)
)
#returns white background
png('tr_tst2.png',width=300,height=300,units="px",bg = "transparent")
print(p)
dev.off()

어떤 이유로 업로드된 이미지가 제 컴퓨터와 다르게 표시되어 있어서 생략했습니다.하지만 저는 상자 그림의 상자 부분을 제외하고는 완전히 회색 배경의 그림을 얻습니다. 상자 그림의 상자 부분은 여전히 흰색입니다.그것은 박스 플롯 지오메트리의 필 에스테틱을 사용하여 변경할 수도 있다고 생각합니다.

편집

ggplot2는 그 이후로 업데이트되었고,opts()기능이 더 이상 사용되지 않습니다.현재, 당신은 사용할 것입니다.theme()대신에opts()그리고.element_rect()대신에theme_rect(),기타.

YCR의 답변을 개선하기 위해:

저는 x축과 y축에 검은색 선을 추가했습니다.그렇지 않으면 그것들도 투명해집니다.

범례 키에 투명 테마를 추가했습니다.그렇지 않으면, 당신은 그곳에서 배가 부를 것이고, 그것은 그리 심미적이지 않을 것입니다.

마지막으로 pdf 및 png 형식에서만 작동합니다. jpeg는 투명 그래프를 생성하지 못합니다.

MyTheme_transparent <- theme(
    panel.background = element_rect(fill = "transparent"), # bg of the panel
    plot.background = element_rect(fill = "transparent", color = NA), # bg of the plot
    panel.grid.major = element_blank(), # get rid of major grid
    panel.grid.minor = element_blank(), # get rid of minor grid
    legend.background = element_rect(fill = "transparent"), # get rid of legend bg
    legend.box.background = element_rect(fill = "transparent"), # get rid of legend panel bg
    legend.key = element_rect(fill = "transparent", colour = NA), # get rid of key legend fill, and of the surrounding
    axis.line = element_line(colour = "black") # adding a black line for x and y axis
)

학술 편집자처럼 회색 배경을 좋아하지 않는 사람은 다음과 같이 하십시오.

p <- p + theme_bw()
p

저는 이것이 R Markdown 내에서 일하고 있고 사용하고 싶지 않은 사람들에게 효과가 있을 것이라고 믿습니다.ggsave별도의 파일을 저장합니다.

다음을 수행하고 이 청크 옵션을 추가합니다.{r, dev.args = list(bg = 'transparent')}:

ggplot(mtcars, aes(wt, mpg)) +
   geom_point() +
   theme(
     # makes background transparent:
     plot.background = element_rect(fill = "transparent",colour = NA),
     # gets rid of white border around plot: 
     panel.border = element_blank() 
   )

예를 들어, 저는 R Markdown 내에서 ioslides 프레젠테이션을 사용하고 있지만, 이 맥락에서 이를 테스트하지는 않았습니다.

카이로 패키지를 사용하여 ggplot을 투명 배경의 이미지로 저장할 수 있습니다.https://cran.r-project.org/web/packages/Cairo/Cairo.pdf

CairoPNG(filename = "TEST.png", bg = "transparent")

ggplot(mtcars, aes(wt, mpg))+
   geom_point()+
   theme(panel.background = element_rect(fill = "transparent"),
      plot.background = element_rect(fill = "transparent", colour = NA))

dev.off()

언급URL : https://stackoverflow.com/questions/7455046/how-to-make-graphics-with-transparent-background-in-r-using-ggplot2

반응형