簡體   English   中英

使用R中的facet_grid的軸混亂的重疊數據

[英]Overlapped data with messed up axises using facet_grid in R

我正在使用構面網格生成我的數據的簡潔演示。 基本上,我的數據框有四列:

idx,密度,標記,大小寫。

有5種情況,每種情況對應5個標記,每個標記對應多個idx,每個idx對應一個密度。

數據上傳到這里: 數據框鏈接

我嘗試使用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)

編輯:

我重新上傳了文件,現在應該可以了: 在這里下載文件

所有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調用的上述代碼,然后比較差異。

正如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

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM