gpt4 book ai didi

r - 如何使用ggplot2在R中制作具有透明背景的图形?

转载 作者:行者123 更新时间:2023-12-03 04:39:31 24 4
gpt4 key购买 nike

我需要将 ggplot2 图形从 R 输出到具有透明背景的 PNG 文件。基本 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
)

修改上图以获得完全透明背景的最快方法是设置 theme()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来设置

Background colour. If NULL, uses the plot.background fill value from the plot theme.

使用透明背景将 ggplot 对象 p 写入磁盘上的 filename:

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

关于r - 如何使用ggplot2在R中制作具有透明背景的图形?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7455046/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com