79257783

Date: 2024-12-06 11:19:19
Score: 1
Natty:
Report link

Using both ggforce's geom_link and ggnewscale, it is possible to make a loop, element by element, creating a new colorscale for each of them:

library(ggforce)
library(ggnewscale)

## Index with colors
color_list <- c('ControlD1' = "limegreen", 
                             'HSP90iD1' = "firebrick1", 
                             'PRRTD1' = "deepskyblue", 
                             'CombinationD1' = "orchid1", 
                             'HSP90iD3' = "firebrick4", 
                             'PRRTD3' = "deepskyblue3", 
                             'CombinationD3' = "purple3")

## old-ish code
p_left <- ggplot(tb_deg) +
  geom_segment(aes(y=comparison, x=var1, xend=var2), size=2, color="slategrey", show.legend = F) +
  geom_point(aes(y=comparison, x=var1, fill=var1), shape=21, size=5, show.legend = F) +
  geom_point(aes(y=comparison, x=var2, fill=var2), shape=21, size=5, show.legend = F) +
  scale_fill_manual(name="Group",
                    values=color_list ) +
  scale_x_discrete(limits=rev(levels(md$group)) ) +
  theme_minimal() +
  labs(x=NULL, y=NULL, title = NULL) +
  theme(legend.position = "none",
        aspect.ratio = 2,
        axis.text.x = element_text(angle=90, hjust=1),
        axis.text.y = element_blank(),
        panel.grid.major.y = element_blank())



p_left

### Loop through each element of the Y-axis, creating a geom_link + a new color scale
p2<-p_left

for (comp in unique(tb_deg$comparison)) {

  v1 <-   unique(tb_deg[tb_deg$comparison==comp, c("comparison","var1","var2")])$var1
  v2 <-   unique(tb_deg[tb_deg$comparison==comp, c("comparison","var1","var2")])$var2

p2 <- p2 +
  new_scale_color() +
  geom_link(data=unique(tb_deg[tb_deg$comparison==comp, c("comparison","var1","var2")]),
            aes(y=comparison, yend=comparison, x=var1, xend=var2, color=stat(index)), size=2) +
  scale_color_gradient(high=color_list[v2],low=color_list[v1])
  
}

p2

geom_link_manually_in_loop

Reasons:
  • Probably link only (1):
  • Long answer (-1):
  • Has code block (-0.5):
  • Self-answer (0.5):
  • Low reputation (1):
Posted by: dkysh