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

标签 r ggplot2 themes r-markdown donut-chart

如何更改 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,手动绘制黑色背景,然后使用参数newpage = FALSE<显式print你的ggplot/。您也可以设置网格 gpar 参数,使背景默认为黑色,但这可能会在以后产生不需要的副作用。

这是带有一些虚构数据的表示:

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/

相关文章:

r - 绘制混合效应模型的预测区间

r - R中的ggplot或qplot直方图

javascript - JQuery Mobile 默认数据主题

r - 在 R 中对同名的列进行分组

r - 拆分一个 rle 对象

r - 多变量图的 geom_segment 线垂直

css - 2.3 Nopcommerce 主题更新到3.0了?

asp.net - css文件的问题

r - R中的异步服务器或快速加载状态

r - 如何使用 R 从 Yahoo Finance 抓取财务数据