Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I indicate groups (such as chromosomes) on a continuous axis using ggplot2?

This is what I want to plot:

enter image description here

Using ggplot2, I can plot the correct bars, but with the locus number stated on the x-axis instead of the chromosome number. It just plots the number of each bar, like 1,2,...,500, but it doesn't show the chromosome. How can I achieve this?

Reproducible example:

p <- ggplot(data = info, aes(x = number,y= Fst,fill = Chromesome))
p + geom_bar(stat = "identity") + labs(x = "Chromosome", y =Fst)

number Chromosome   Fst
1       1           0.5
2       1           0.6
3       2           0.7
4       2           0.9
5       3           0.7
6       3           0.1
7       4           0.3
8       4           0.4
9       5           0.5
10      5           0.6
11      6           0.7
12      6           0.8
13      7           0.9
like image 351
Ziv Avatar asked Sep 19 '25 02:09

Ziv


1 Answers

The obvious way would be to use scale_x_continuous and set manual breaks and labels, however...

One way I have used before is to use facets with free scales and space.

Create some random data

info <- data.frame(number = 1:800,
                   Fst = runif(800),
                   Chromosome = rep(1:5, c(300, 200, 100, 100, 100)))

Your plot

Note that you had some spelling mistakes which caused errors.

p <- ggplot(data = info, aes(x = number, y = Fst, fill = factor(Chromosome))) +
  geom_bar(stat = "identity") + labs(x = "Chromosome", y = "Fst")

enter image description here

Add facets and customize theme

p + facet_grid(~Chromosome, scales = 'free_x', space = 'free_x', switch = 'x') + 
  theme_classic() + 
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        panel.margin = unit(0, "lines"))

enter image description here

You can turn off axis expansion to get the bars to be exactly next to each other, but personally I quite like the gaps.

p + facet_grid(~Chromosome, scales = 'free_x', space = 'free_x', switch = 'x') + 
  theme_classic() + 
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        panel.margin = unit(0, "lines")) +
  scale_x_continuous(expand = c(0, 0))

enter image description here

like image 122
Axeman Avatar answered Sep 20 '25 15:09

Axeman