【问题标题】:Create ggplots with the same scale in R在 R 中创建具有相同比例的 ggplots
【发布时间】:2017-01-20 16:31:50
【问题描述】:

我想在 R 中执行以下操作:我有 2 个数据集(一个由 4 个组成,另一个由 3 个值组成),我想用 ggplot2 将它们绘制为条形图(单独)。但是,我想对两者使用相同的比例,即:如果数据集 #1 的最小值是数据集 #2 的 0.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)条的高度和颜色的比例(因此将图像精确地移动在一起表明具有相同高度但属于不同图像的条以相同的方式显示并且它们的颜色相同)?

【问题讨论】:

  • 您可以尝试将min(min(dataset1), min(dataset2)) 作为您的第一个ylim() 参数。
  • 非常感谢,试过了,几乎和下面的答案一样(除了调整)。
  • 您可以在scale_fill_gradient2 中设置limits 以保持绘图之间的填充比例相同。

标签: r ggplot2 scale bar-chart


【解决方案1】:

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

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);

【讨论】:

  • 令人印象深刻的答案,非常感谢。 :) 唯一没有解决的是着色。对常见的色阶有什么想法(0.65 和 1.2 肯定有相同的黄色,但字母应该至少是橙色或红色)?
  • 设法解决了我自己的着色问题(为scale_fill_gradient2 属性的每个绘图提供不同的着色参数)。感谢您的宝贵时间。
【解决方案2】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-05
    • 2011-06-28
    • 1970-01-01
    • 1970-01-01
    • 2019-10-17
    • 1970-01-01
    • 2013-04-03
    • 2021-10-11
    相关资源
    最近更新 更多