1

I have a table with coordinate data that looks like this,

V1       V2      V3       V4    
10253363 10273825 9982154 10003803     
10265080 10285697 9993266 10015040     
10250800 10271301 9979709 10001394     
10254775 10275140 9983264 10004815     
10268607 10288871 9995004 10016450     
10263978 10284276 9992831 10014300  

And I'd like to generate a plot similar to the one shown below, enter image description here

I tried this,

blast <- fread("../plots/coords.tsv")
blast$id = as.numeric(rownames(blast))
ggplot(blast)+ 
  geom_rect(aes(xmin=V1,xmax=V2,ymin=V3,ymax=V4, group = id), alpha=0.2) + 
  scale_y_continuous(position = "top") 

and ended up with the plot below instead.

enter image description here It seems like y axis position could only be flipped between right and left. Therefore, this isn't working for me.

How do I generate the intended plot in ggplot2? Or is there another way to get at that?

Axeman
  • 32,068
  • 8
  • 81
  • 94
user2960593
  • 87
  • 2
  • 10

1 Answers1

0

That's not so easy, as you need to reshape and then trick ggplot2 a little.

The conversion factor is needed, since ggplot doesn't really allow separate axes, only relabeling based on simple conversions.

Also see this related answer.

You have a bunch of overlapping ranges, so it doesn't quite look like your example plot.

library(tidyr)
library(dplyr)
library(ggplot2)

conversion_factor <- mean(c(blast$V3, blast$V4)) / mean(c(blast$V1, blast$V2))
blast2 <- mutate(blast, V3 = V3 / conversion_factor, V4 = V4 / conversion_factor)

blast_long <- blast2 %>% 
  gather(var, x, -id) %>% 
  group_by(id) %>% 
  mutate(y = c(0, 0, 1, 1), 
         order = c(1, 2, 4, 3)) %>% 
  arrange(order)

ggplot(blast_long, aes(x, y, group = id))+ 
  geom_polygon(alpha = 0.3) +
  scale_x_continuous(sec.axis = sec_axis(~ . * conversion_factor))

enter image description here

Axeman
  • 32,068
  • 8
  • 81
  • 94
  • Thanks for the response, Axeman. I guess my post didn't come across as I intended. clear. sec_axis only seems to be adding the x axis labels on the top. Ideally what I want is just two axes with the x axis (limits will be based on columns V1 and V2) at the bottom and the y axis (with limits based on V3, V4) on the top. Then I'd like to have rectangles/segments drawn between these two axes. – user2960593 Dec 04 '17 at 12:33