简体   繁体   中英

Overlapped data with messed up axises using facet_grid in R

I am using facet grid to generate neat presentations of my data. Basically, my data frame has four columns:

idx, density, marker, case.

There are 5 cases, each case corresponds to 5 markers, and each marker corresponds to multiple idx, each idx corresponds to one density.

The data is uploaded here: data frame link

I tried to use facet_grid to achieve my goal, however, I obtained a really messed up graph: 在此处输入图片说明

The x-axis and y-axis are messed up, the codes are:

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)

EDIT:

I reupload the file, now it should be work: download file here

All 4 columns have been read as factors. This is an issue from however you loaded the data into R. Take a look at:

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 ...

Good news is that you can fix it with:

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

Although you should look into how you are loading the data, to avoid future.

As another trick, try the above code without using the as.character calls, and compare the differences.

As already explained by MrGumble , the idx and density variables are of type factor but should be plotted as numeric.

The type.convert() function does the data conversion in one go:

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

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM