我想做的是創建一個條形圖,而不是顯示 x 軸標簽,我想嘗試用單獨的圖替換標簽。希望我下面的示例和嘗試的解決方案能夠解釋這個問題。
首先,我創建一個條形圖,然后創建多個單獨的圖以在 x 軸上顯示,如下所示:
library(ggplot)
# create barplot ----------------------------------------------------------
df <- data.frame(vals = c(10, 5, 18),
name = c("A", "B", "C"))
bp <- df %>%
ggplot()
geom_bar(aes(x = name, y = vals), stat = "identity")
xlab("")
theme_bw()
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())
# create plots to use as x-axis --------------------------------------------
p1 <- ggplot(df, aes(x = vals, y = vals)) geom_point() theme_bw()
theme(axis.title.x = element_blank(),
axis.text.x = element_blank(),
axis.ticks.x = element_blank(),
axis.title.y = element_blank(),
axis.text.y = element_blank(),
axis.ticks.y = element_blank())
p3 <- p2 <- p1
# turn into list of plots
myList <- list(p1, p2, p3)
嘗試的解決方案:
我嘗試的解決方案是使用該patchwork包將 x 軸標簽替換為單個圖,如下所示:
library(patchwork)
# setting positions manually
design <- c(
area(1, 1, 4, 4),
area(5,1),
area(5,3),
area(5,4)
)
bp myList plot_layout(design = design)
這看起來像:

但是正如您所看到的,這并沒有將相應條下的各個圖對齊。如果條形圖中使用的條形超過 3 個,對齊問題也會更加復雜。
此外,必須使用該patchwork::area功能手動設定位置并不理想。
是否可以創建一個條形圖,其中 x 軸顯示一堆單獨的圖,而我不必手動定位它們?
uj5u.com熱心網友回復:
通過實作您想要的結果的一種選擇patchwork是
- 創建一個 ggplot 使用
geom_blank(aes(x=name))(以獲得與條形圖中相同的軸) - 通過
annotation_custom我使用的位置添加要用作軸標簽的圖purrr::map2 - 通過洗掉所有非資料墨水
theme_void - 用于
patchwork將“軸圖”粘貼到條形圖上
library(ggplot2)
library(patchwork)
width <- .9 # Default width of bars
p_axis <- ggplot(df)
geom_blank(aes(x = name))
purrr::map2(myList, seq_along(myList), ~ annotation_custom(ggplotGrob(.x), xmin = .y - width / 2, xmax = .y width / 2))
theme_void()
library(patchwork)
bp / p_axis plot_layout(heights = c(4, 1))

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/352292.html
上一篇:在Shiny中按周順序調整選擇
