简体   繁体   中英

Colour geom_segment in ggplot2 according to segment length

I have a graph that displays the distortion of points by connecting the original and new location. I would like to visualise the level of distortion by colouring the segments according to their length. As visible in the uncoloured graph the distortion centre is at around [0,300] and amplifies towards [300,0].

图形的当前无色版本

I was hoping to find a way to feed the segment length into the colour option of geom_segment, but I could not find an internal way of ggplot2 to do so. Do I have to manually compute the length and store it in the data frame, or is there a more elegant way? I was hoping something along the lines of feeding the respective segments length property to colour and use some colour range to signify length.

Edit: A link to the data on display.

As well as some code:

library(readr)
library(ggplot2)

data<-read_csv("distortedGraph.csv",col_names = F)

ggplot(data = data) +
  geom_segment(aes(x = X2, xend = X4, y = X3, yend = X5)) +
  scale_x_continuous(limits = c(-50, 350))+
  scale_y_continuous(limits = c(-50, 350))+
  coord_fixed()

I think it is easiest to just manually give the distance formula, it's not all that complicated. geom_segment does not calculate a distance statistic for you. Add a nice color palette and you should be good to go:

ggplot(dat, 
       aes(x = X2, xend = X4, y = X3, yend = X5,
           color = sqrt((X2 - X4)^2 + (X3 - X5)^2))) +
  geom_segment(alpha = 0.5) +
  scale_x_continuous(limits = c(-50, 350))+
  scale_y_continuous(limits = c(-50, 350))+
  coord_fixed() +
  viridis::scale_color_viridis(name = 'distance')

在此处输入图片说明

While @Axeman provided the exact answer I was looking for, I looked into @markus's comment and concluded that geom_link in ggforce would provide a different, but also interesting analysis of the level of distortion each point experienced by applying a gradient along the distortion line:

library(ggforce)
ggplot(data = data) +
  geom_link(aes(x = X2, xend = X4, y = X3, yend = X5,colour = ..index..)) +
  scale_x_continuous(limits = c(-50, 350))+
  scale_y_continuous(limits = c(-50, 350))+
  coord_fixed()+
  viridis::scale_color_viridis(name = 'distortion', option = "C", direction = -1)

用梯度绘制失真度

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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