r - 在facet_wrap中,如何将第二行向右对齐?

标签 r ggplot2

我有下图。如何将第二行向右对齐?谢谢!

最佳答案

根据 this回答您可以将绘图作为网格对象进行操作。

library(ggplot2)
library(dplyr)
library(grid)
# inject blank level into factor
d1 <- mutate(mtcars, 
    carb = factor(replace(carb, carb == 8, 6), 
        levels = c(1:3, 0, 4, 6), 
        labels = c("Replay-Say", "Replay-Project", "Replay-Proj-Say", 
            "", "Project", "Project-Say")))
p1 <- ggplot(data = d1, 
    mapping = aes(x = factor(cyl))) + 
    geom_bar() + xlab("") + ylab("") + facet_wrap(~carb, drop = FALSE)
p1
facetted bar chart with blank panel
根据绘图的布局,您需要确定要删除的面板名称和刻度线。
g1 <- ggplotGrob(p1)
g1$layout$name
#  [1] "background"  "panel-1-1"   "panel-3-1"   "panel-1-2"   "panel-2-2"  
#  [6] "panel-3-2"   "axis-t-1-2"  "axis-t-2-2"  "axis-t-3-2"  "axis-t-1-1" 
# [11] "axis-t-2-1"  "axis-t-3-1"  "axis-b-1-2"  "axis-b-2-2"  "axis-b-3-2" 
# ...
然后,您可以从图中删除这些。字母分配似乎是顶部(“t”)、底部(“b”)、左侧(“l”)、右侧(“r”)。
blank_panel_grobs <- c("panel-2-1", "strip-t-1-2", "axis-b-1-2", "axis-l-2-1")
blank_panel_index <- g1$layout$name %in% blank_panel_grobs
g1$layout <- lapply(g1$layout, function(x) x[!blank_panel_index])
g1$grobs <- g1$grobs[!blank_panel_index]
grid.draw(g1)
facetted bar chart with removed panel

关于r - 在facet_wrap中,如何将第二行向右对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68216901/

相关文章:

r - 如何转换时间 HH :MM:SS to decimal form in R?

R-boxplot 设置为 2 个小数位

r - 如何将 R revel.js 演示文稿转换为 pdf?

r - highcharts 中的分面函数

r - ggplot2 - 大小单位

r - 在 data.table 中插入一行

r - 解析不同格式的日期

r - 使用 ggplot 可视化正/负时间序列数据的优雅方法?

r - ggplot2 stat_密度_2d 分组时无法正常工作

r - 使用 show.legend = FALSE 删除图例不适用于连续美学