简体   繁体   English

ggplot2中,x轴在底部,y轴在顶部?

[英]plot with x axis at the bottom and y axis on top in ggplot2?

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, 我想生成一个类似于以下所示的图, 在此处输入图片说明

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. 并最终显示为下面的图。

在此处输入图片说明 It seems like y axis position could only be flipped between right and left. 看来y轴位置只能在左右之间翻转。 Therefore, this isn't working for me. 因此,这对我不起作用。

How do I generate the intended plot in ggplot2 ? 如何在ggplot2生成预期的图? Or is there another way to get at that? 还是有其他方法可以做到这一点?

That's not so easy, as you need to reshape and then trick ggplot2 a little. 这不是那么容易,因为您需要重塑形状然后再欺骗ggplot2。

The conversion factor is needed, since ggplot doesn't really allow separate axes, only relabeling based on simple conversions. 需要转换因子,因为ggplot确实不允许单独的轴,只能基于简单转换进行重新标记。

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

在此处输入图片说明

I've found the riverplot library, I think It's a possible solution for your problem. 我已经找到了riverplot库,我认为这可能是解决您的问题的方法。

Another possible solution could be slopegraphs , I would start by this way. 另一个可能的解决方案是坡度图 ,我将以此方式开始。 I have found an example on Github: Slopegraphs in R with ggplot2 我在Github上找到了一个示例: R中带有ggplot2的坡度图

I hope you find this information useful. 我希望这个信息对您有所帮助。

References: 参考文献:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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