在 R 中创建具有相同比例的 ggplots

Create ggplots with the same scale in R

我想在 R 中执行以下操作:我有 2 个数据集(一个由 4 个值组成,另一个由 3 个值组成),我想用 ggplot2 将它们绘制为条形图(分别)。但是,我想对两者使用相同的比例,即:如果数据集 #1 的最小值是 0.2 和数据集 #2 的 0.4,那么我想对两者都使用 0.2。同样适用于最大值(选择较大的值)。

所以,基本上,我想让这两个地块具有可比性。当然,也可以应用通用比例为条形着色。现在,我正在使用 colorRampPalette 并将其应用到 scale_fill_gradient2 属性.

下面提供了一个 MWE:

library("ggplot2")
val <- c(0.2, 0.35, 0.5, 0.65)
labels <- c('A', 'B', 'C', 'D')

LtoM <-colorRampPalette(c('green', 'yellow'))

df <- data.frame(val)
bar <- ggplot(data = df,
              aes(x = factor(labels),
                  y = val,
                  fill = val)) +
  geom_bar(stat = 'identity') + 
  scale_fill_gradient2(low=LtoM(100), mid='snow3', 
                       high=LtoM(100), space='Lab') +
  geom_text(aes(label = val), vjust = -1, fontface = "bold") +
  labs(title = "Title", y = "Value", x = "Methods") +
  theme(legend.position = "none")
print(bar)

鉴于上面的代码,以及另一个数据集,如 c(0.4, 0.8, 1.2) 和标签 c('E', 'F', 'G'),如何调整代码以创建 2 个不同且分离的图(最终保存到 PNG 中,即)但使用条形高度及其颜色的通用 (0.2 to 1.2) 比例(因此将图像恰好并排移动表示具有相同高度但属于不同图像的条形以相同方式出现,并且它们的颜色是一样)?

我们可以在 scale_y_continuous 中混合使用 breaks 参数来确保我们有一致的轴刻度,然后使用 coord_cartesian 来确保我们强制两个图都有相同 y-axis 范围。

df1 <- data.frame(val = c(0.2, 0.35, 0.5, 0.65), labels = c('A', 'B', 'C', 'D'))
df2 <- data.frame(val = c(0.4, 0.8, 1.2), labels = c('E', 'F', 'G'))

g_plot <- function(df) {
    ggplot(data = df,
          aes(x = factor(labels),
              y = val,
              fill = val)) +
        geom_bar(stat = 'identity') + 
        scale_fill_gradient2(low=LtoM(100), mid='snow3', 
                     high=LtoM(100), space='Lab') +
        geom_text(aes(label = val), vjust = -1, fontface = "bold") +
        scale_y_continuous(breaks = seq(0, 1.2, 0.2)) + 
        coord_cartesian(ylim = c(0, 1.2)) + 
        labs(title = "Title", y = "Value", x = "Methods") +
        theme(legend.position = "none")
}

bar1 <- g_plot(df1);
bar2 <- g_plot(df2);
gridExtra::grid.arrange(bar1, bar2, ncol = 2);

您实际上不需要使用 coord_cartesian。您可以只使用 scale_y_continuous 中的 limits 参数,如下所示:

scale_y_continuous(limits = c(0,1.2), breaks = seq(0, 1.2, 0.2))