Home > Back-end >  Apply gradient colors on multiple arrows generated by geom_segment() or geom_link()
Apply gradient colors on multiple arrows generated by geom_segment() or geom_link()

Time:11-18

I would like to draw several arrows which indicate vectors whose origins are at (0,0) in a coordinate system. Here is the data (arrow):

    x1 y1          x2           y2
1   0  0  0.03547301 -0.122964349
2   0  0  0.10231616  0.467737581
3   0  0  0.07178671  0.009871989
4   0  0  0.08409951  0.005768529
5   0  0  0.07555414  0.311021699
6   0  0 -0.01020843 -0.024377519
7   0  0  0.04818488 -0.016939487
8   0  0 -0.07599210 -0.182464675
9   0  0  0.21804318 -0.159189789
10  0  0  0.10697846 -0.070381673
11  0  0 -0.09771545 -0.082626031
12  0  0  0.03568008 -0.047201735
13  0  0  0.08981450 -0.232150118
14  0  0  0.08084139  0.010385412
15  0  0  0.26188552  0.425836906
16  0  0 -0.91098873 -0.180781148
17  0  0  0.03733511  0.036019056
18  0  0 -0.02595595 -0.046080818
19  0  0  0.09674545  0.063773405
20  0  0  0.05841455  0.139450807
21  0  0  0.04352579  0.065334522
22  0  0  0.02618533  0.111700777
23  0  0  0.02068825 -0.054461573
24  0  0 -0.01325943  0.073912948

Simply put, I would like to draw 24 arrows and color them by gradient colors based on their absolute length on the x-axis. However, I'm not sure which part I did incorrectly and all the arrows are still in black. Below are my codes:

p <- ggplot(data = arrows, aes(x = x1, y = y1, xend = x2, yend = y2), color=abs(x2))   
            geom_link(arrow = grid::arrow(length = grid::unit(0.2, 'cm')))
p   ggpubr::gradient_color(c("#00AFBB", "#E7B800", "#FC4E07"))

Thanks for the help!

CodePudding user response:

It looks like you need to place your color parameter inside of your aes()

library(ggforce)
library(ggpubr)


arrows <- data.frame(
                stringsAsFactors = FALSE,
                x1 = rep(c(0), 4), 
                y1 = rep(c(0), 4), 
                x2 = c(0.03547301, 0.10231616, 0.10231616, 0.08409951
                       ), 
                y2 = c(-0.122964349, 0.467737581, 0.009871989, 0.005768529)
)


p <- ggplot(data = arrows, aes(x = x1, y = y1, xend = x2, yend = y2, color=abs(x2)))   
  geom_link(arrow = grid::arrow(length = grid::unit(0.2, 'cm')))
p   ggpubr::gradient_color(c("#00AFBB", "#E7B800", "#FC4E07"))

sampledata

  • Related