【问题标题】:Can I fix overlapping dashed lines in a histogram in ggplot2?我可以在 ggplot2 的直方图中修复重叠的虚线吗?
【发布时间】:2015-02-20 14:24:29
【问题描述】:

我正在尝试在 ggplot2 中绘制两个重叠分布的直方图。不幸的是,图形需要是黑白的。我尝试用不同的灰色阴影和透明度来表示这两个类别,但结果并不像我想要的那样清晰。我尝试为具有不同线型的条添加轮廓,但这产生了一些奇怪的结果。

require(ggplot2)
set.seed(65)
a = rnorm(100, mean = 1, sd = 1)
b = rnorm(100, mean = 3, sd = 1)
dat <- data.frame(category = rep(c('A', 'B'), each = 100),
              values = c(a, b))

ggplot(data = dat, aes(x = values, linetype = category, fill = category)) +
        geom_histogram(colour = 'black', position = 'identity', alpha = 0.4, binwidth = 1) +
        scale_fill_grey()

请注意,其中一条应显示为虚线的线实际上是实线(x = 4)。我认为这一定是因为它实际上是两条线——一条来自 3-4 条,一条来自 4-5 条。这些点是异相的,因此它们会产生一条实线。效果相当丑陋和不一致。

  1. 有没有办法修复这种重叠?
  2. 谁能提出一种更有效的方法来澄清这两个类别之间的区别,而不用借助颜色?

非常感谢。

【问题讨论】:

    标签: r ggplot2 histogram overlap


    【解决方案1】:

    一种可能性是使用“空心直方图”,如here 所述:

    # assign your original plot object to a variable 
    p1 <- ggplot(data = dat, aes(x = values, linetype = category, fill = category)) +
      geom_histogram(colour = 'black', position = 'identity', alpha = 0.4, binwidth = 0.4) +
      scale_fill_grey()
    # p1
    
    # extract relevant variables from the plot object to a new data frame
    # your grouping variable 'category' is named 'group' in the plot object
    df <- ggplot_build(p1)$data[[1]][ , c("xmin", "y", "group")]
    
    # plot using geom_step
    ggplot(data = df, aes(x = xmin, y = y, linetype = factor(group))) +
      geom_step()
    

    如果你想同时改变线型和填充,你需要先绘制一个直方图(可以填充)。将直方图的轮廓颜色设置为透明。然后添加geom_step。使用theme_bw 避免“灰色背景上的灰色元素”

    p1 <- ggplot() +
      geom_histogram(data = dat, aes(x = values, fill = category),
                     colour = "transparent", position = 'identity', alpha = 0.4, binwidth = 0.4) +
      scale_fill_grey()
    
    df <- ggplot_build(p1)$data[[1]][ , c("xmin", "y", "group")]
    df$category <- factor(df$group, labels = c("A", "B"))
    
    p1 +
      geom_step(data = df, aes(x = xmin, y = y, linetype = category)) +
      theme_bw()
    

    【讨论】:

    • 好主意!我以前没有遇到过。谢谢。
    【解决方案2】:

    首先,我推荐theme_set(theme_bw())theme_set(theme_classic())(这会将背景设置为白色,这使得(更)更容易看到灰色阴影)。

    其次,您可以尝试scale_linetype_manual(values=c(1,3)) 之类的方法——这不会完全消除您不满意的伪影,但可能会使它们不那么突出,因为线型 3 比线型 2 更稀疏。

    而不是绘制密度图(这对于小样本来说效果不佳,并且您的观众可能不熟悉),躲避直方图的位置(这很难看),或者以其他方式偏离直方图约定,我想不出更好的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多