chippycentra
chippycentra

Reputation: 3432

geom_segment arrow settings - head same width as line

Hello everyone I would need help in order to get a nice geom_segment plot with ggplot2.

Here are the data

structure(list(molecule = structure(c(1L, 1L, 2L, 2L, 3L, 4L, 
4L, 5L, 6L), .Label = c("scaffold1", "scaffold2", "scaffold3", 
"scaffold4", "scaffold5", "scaffold6"), class = "factor"), gene = structure(1:9, .Label = c("Gene1", 
"Gene2", "Gene3", "Gene4", "Gene5", "Gene6", "Gene7", "Gene8", 
"Gene9"), class = "factor"), start_gene = c(64000L, 80000L, 60000L, 
20000L, 22000L, 20000L, 35000L, 17000L, 2000L), end_gene = c(68000L, 
83000L, 68000L, 28000L, 29000L, 33000L, 38000L, 19000L, 2500L
), start_scaff = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), end_scaff = c(125000L, 
125000L, 80000L, 80000L, 60000L, 40000L, 40000L, 20000L, 5000L
), strand = structure(c(1L, 1L, 1L, 2L, 1L, 2L, 1L, 2L, 1L), .Label = c("forward", 
"reverse"), class = "factor"), direction = c(1L, 1L, 1L, -1L, 
1L, -1L, 1L, -1L, 1L)), class = "data.frame", row.names = c(NA, 
-9L))

Whit these data and this code :

library(ggplot2)

ggplot(tab, aes(x = start_scaff, xend = end_scaff, 
                y = molecule, yend = molecule)) +
  geom_segment(size = 3, col = "grey80") +
  geom_segment(aes(x = ifelse(direction == 1, start_gene, end_gene),
                   xend = ifelse(direction == 1, end_gene, start_gene)),
               data = tab, 
               arrow = arrow(length = unit(0.1, "inches")), size = 2) +
  geom_text(aes(x = start_gene, y = molecule, label = gene),
            data = tab, nudge_y = 0.2) + 
  scale_y_discrete(limits = rev(levels(tab$molecule))) +
  theme_minimal()

I can manage do create this plot :

enter image description here

And I'm looking for settings in order to get the segment more like rectangles with a small arrow such as :

enter image description here

Upvotes: 2

Views: 1177

Answers (1)

tjebo
tjebo

Reputation: 23757

I think you may want to look at the gggenes package - may help you not only for the arrows :)

From the example in the vignette, I used the settings to get the head to the same width as the segment.

Another advantage of using this geom, you can use alpha

library(gggenes)
library(ggplot2)

ggplot(mydat, aes(x = start_scaff, xend = end_scaff, 
                y = molecule, yend = molecule)) +
  geom_segment(size = 3, col = "grey80") +
  geom_gene_arrow(aes(xmin = ifelse(direction == 1, start_gene, end_gene),
                   xmax = ifelse(direction == 1, end_gene, start_gene)),
                  arrowhead_height = unit(3, "mm"), arrowhead_width = unit(1, "mm")) +
  geom_text(aes(x = start_gene, y = molecule, label = gene),
            data = mydat, nudge_y = 0.2) + 
  scale_y_discrete(limits = rev(levels(mydat$molecule))) +
  theme_minimal()

Upvotes: 2

Related Questions