gpt4 book ai didi

r - 如何更改 donut ggplot 图中的 plot.background?

转载 作者:行者123 更新时间:2023-12-04 16:11:48 25 4
gpt4 key购买 nike

如何在 Donut ggplot 图中更改“geom_rect()”+“coord.polar()”中的 plot.background?
我不知道我错过了什么,但是我在 html 黑色背景样式中工作并且需要将面板以及绘图背景设置为黑色,但是我的 ggplot 的图形边是白色的,我需要知道我的哪个属性或命令也需要使用将侧面变成黑色。
在我的代码下面:

my_df %>% 
ggplot(aes(ymax=max, ymin=min, xmax=4, xmin=3,fill=ResultCode)) +
geom_rect() +
geom_label( x=3.5, aes(y=labelPosition, label=label), size=4, color="white") +
coord_polar(theta="y") +
xlim(c(2, 4)) +
theme_void() +
theme(legend.position="none",
plot.background=element_rect(fill = "black"),
panel.background = element_rect(fill = "black"),
panel.border = element_blank(),
legend.key = element_blank(),
axis.ticks = element_blank(),
axis.text.y = element_blank(),
panel.grid = element_blank())
在结果图下方(请参阅左右两侧的“白色”边,我需要用黑色填充)
enter image description here

最佳答案

这里的问题是 ggplot默认调用 grid::grid.newpage在画之前。这将创建一个空白(白色)屏幕。然后它将设置一个方形视口(viewport)以适合您的绘图窗口,因为您使用的是 coord_polar .完成此操作后,它会将方形区域视为“该”绘图窗口。从某种意义上说,ggplot 不知道或控制这些白色区域。否 theme元素可以触摸它。
解决方法是显式调用grid.newpage自己,手动绘制黑色背景,然后明确print您的 ggplot 使用参数 newpage = FALSE .您也可以设置网格 gpar参数,以便默认情况下背景为黑色,但这可能会在以后产生不良副作用。
这是一个带有一些虚构数据的 reprex:

my_df <- data.frame(max = c(160, 320), min = c(0, 161), 
ResultCode = c("A","B"),
labelPosition = c(80, 240), label = c("A", "B"))

p <- my_df %>%
ggplot(aes(ymax=max, ymin=min, xmax=4, xmin=3,fill=ResultCode)) +
geom_rect() +
geom_label( x=3.5, aes(y=labelPosition, label=label), size=4, color="white") +
coord_polar(theta="y") +
xlim(c(2, 4)) +
theme(legend.position="none",
plot.background = element_rect(fill = "black", color = "black"),
panel.background = element_rect(fill = "black", color = "black"),
plot.margin = margin(0,0,0,0),
panel.border = element_blank(),
legend.key = element_blank(),
axis.ticks = element_blank(),
axis.text.y = element_blank(),
panel.grid = element_blank())

grid::grid.newpage()
grid::grid.draw(grid::rectGrob(gp = grid::gpar(fill = "black")))
print(p, newpage = FALSE)
enter image description here

关于r - 如何更改 donut ggplot 图中的 plot.background?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64297387/

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