Home > Mobile >  Maintain space between bars regardless of sample numbers
Maintain space between bars regardless of sample numbers

Time:12-14

I want to make several plots same space interval between bars regardless of sample numbers

As described below.

enter image description here

Not like this

enter image description here

My original script is

myData <- read.csv('L1L2_100percent.csv', header = T, sep =',')

ggplot(data = myData, aes(x = region, y = vaf, fill = type))   
 geom_bar(stat = "identity", width = 0.4)  
 coord_flip()

I think it has to do with saving pictures with a specific height, but I think the height has to be determined with sample numbers but I don't know the exact value.

CodePudding user response:

You just need to adjust the height of the plot on saving proportional to the number of bars. Here, plt1 has 5 instead of 10 bars thus it should be saved with a height that is only half than those of plt2:

library(tidyverse)

# create example data
myData <-
  iris %>% transmute(
    region = row_number() %% 20,
    vaf = Sepal.Length,
    type = Species
  )

plt1 <-
  myData %>%
  filter(region < 5) %>%
  ggplot(aes(x = region, y = vaf, fill = type))   
  geom_bar(stat = "identity")  
  coord_flip()

plt2 <-
  myData %>%
  filter(region < 10) %>%
  ggplot(aes(x = region, y = vaf, fill = type))   
  geom_bar(stat = "identity")  
  coord_flip()

ggsave("plt1.png", plt1, height = plt1$data$region %>% unique() %>% length())
ggsave("plt2.png", plt2, height = plt2$data$region %>% unique() %>% length())

Plt1: enter image description here

Plt2: enter image description here

  • Related