[英]How to easily maintain the same axis scale for two histograms
看到了一些類似的代碼,但我很好奇“gridExtra”package 是否可行。我想在 x 軸和 y 軸的相同比例上顯示這些代碼。 箱線圖也需要這樣做。 使用 grid.arrange() 有更簡單的方法嗎?
library(tidyverse)
library(gridExtra)
#Subset of Data
za <- structure(list(sodium = c(1.77, 1.79, 1.63, 1.61, 1.64, 1.65,
1.58, 1.75, 1.71, 1.66), cal = c(4.93, 4.84, 4.95, 4.74, 4.67,
4.67, 4.63, 4.72, 4.93, 4.95)), class = c("tbl_df", "tbl", "data.frame"
), row.names = c(NA, -10L))
#Histogram
sodHist <- ggplot(data = za, mapping = aes(x = sodium)) +
geom_histogram(fill = "royalblue1", color = "white") +
ggtitle("Sodium Distribution of Pizzas")
calHist <- ggplot(data = za, mapping = aes(x = cal)) +
geom_histogram(fill = "limegreen", color = "white") +
ggtitle("Calorie Distribution of Pizzas")
grid.arrange(sodHist,calHist, ncol = 2)
問題是您將兩個 grobs 喂入grid.arrange
並且軸已經設置好。 使 y 軸相等的最干凈的方法可能是“破解”底層的 ggplots 並使它們的軸在內部相等:
grid.arrange.equal <- function(plotA, plotB, ...)
{
A <- ggplot_build(plotA)
B <- ggplot_build(plotB)
if(A$layout$panel_scales_y[[1]]$range$range[2] > B$layout$panel_scales_y[[1]]$range$range[2])
B$layout$coord$limits$y <- A$layout$panel_scales_y[[1]]$range$range
else
A$layout$coord$limits$y <- B$layout$panel_scales_y[[1]]$range$range
grid.arrange(A$plot, B$plot, ...)
}
所以現在你可以這樣做:
grid.arrange.equal(calHist, sodHist, ncol=2)
您的示例中的數據有點短,無法提供漂亮的直方圖,但您明白了:
使用更真實的虛擬數據:
我會 go 與r2evans建議的方面
za %>%
mutate(num = row_number()) %>% # add rownumbers to allow the pivoting
pivot_longer(-num, names_to = "atom", values_to = "val") %>%
ggplot(aes(x = val, col = atom, fill = atom)) +
geom_histogram() +
facet_wrap(~atom)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.