【问题标题】:Overlapped data with messed up axises using facet_grid in R在 R 中使用 facet_grid 的重叠数据与混乱的轴
【发布时间】:2019-08-28 05:45:03
【问题描述】:

我正在使用分面网格来生成我的数据的简洁表示。 基本上,我的数据框有四列:

idx、密度、标记、大小写。

有5个case,每个case对应5个marker,每个marker对应多个idx,每个idx对应一个密度。

数据上传到这里: data frame link

我尝试使用 facet_grid 来实现我的目标,但是,我得到了一个非常混乱的图表:

x轴和y轴打乱了,代码是:

library(ggplot2)
library(cowplot)
plot.density <-
  ggplot(df_densityWindow, aes(x = idx, y = density)) +
  geom_col() +
  facet_grid(marker ~ case, scales = 'free') +
  background_grid(major = 'y', minor = "none") + # add thin horizontal lines
  panel_border() # and a border around each panel
plot(plot.density)

编辑:

我重新上传了文件,现在它应该可以工作了: download file here

【问题讨论】:

  • 你能显示str(df_densityWindow)吗? x 和 y 是某种因素吗?
  • 坐标轴表示您的输入变量 idsdensity 被读取为不同的分类值,而不是连续数据。所以ggplot 尝试标记每个变量。正如其他评论员所评论的那样显示您的数据框的结构,但我怀疑这个问题部分与您加载数据的方式有关。此外,您链接到的文件在我的计算机上是空的。
  • @MrGumble 感谢您的评论!我添加了一个新链接,现在应该可以使用了!

标签: r ggplot2 facet-wrap facet-grid


【解决方案1】:

所有 4 列都被视为因子。这是一个问题,因为您将数据加载到 R 中。看看:

df <- readRDS('df.rds')
str(df)
'data.frame':   52565 obs. of  4 variables:
 $ idx    : Factor w/ 4712 levels "1","10","100",..: 1 1112 2223 3334 3546 3657 3768 3879 3990 2 ...
 $ density: Factor w/ 250 levels "1022.22222222222",..: 205 205 204 203 202 201 199 198 197 197 ...
 $ marker : Factor w/ 5 levels "CD3","CD4","CD8",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ case   : Factor w/ 5 levels "Case_1","Case_2",..: 1 1 1 1 1 1 1 1 1 1 ...

好消息是您可以通过以下方式修复它:

df$idx <- as.integer(as.character(df$idx))
df$density <- as.numeric(as.character(df$density))

尽管您应该研究如何加载数据,以避免将来发生。

作为另一个技巧,使用as.character调用尝试上面的代码,并比较差异。

【讨论】:

    【解决方案2】:

    正如MrGumble 已经解释的那样,idxdensity 变量属于类型因子,但应绘制为数字。

    type.convert() 函数一次性完成数据转换:

    library(ggplot2)
    library(cowplot)
    ggplot(type.convert(df_densityWindow), aes(x = idx, y = density))    + 
      geom_col() + 
      facet_grid(marker ~ case, scales = 'free') +
      background_grid(major = 'y', minor = "none") + # add thin horizontal   lines 
      panel_border() # and a border around each panel
    

    【讨论】:

      猜你喜欢
      • 2020-11-16
      • 1970-01-01
      • 1970-01-01
      • 2021-03-29
      • 2013-11-03
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 2020-11-17
      相关资源
      最近更新 更多