根据段长度在ggplot2中颜色geom_segment [英] Colour geom_segment in ggplot2 according to segment length

查看:116
本文介绍了根据段长度在ggplot2中颜色geom_segment的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图形,它通过连接原始位置和新位置来显示点的变形.我想通过根据分段的长度为分段着色来形象化失真的程度.如在无色图中可见,失真中心在[0,300]附近,并向[300,0]放大.

我希望找到一种将段长度输入geom_segment的color选项的方法,但是我找不到ggplot2的内部方法.我是否必须手动计算长度并将其存储在数据框中,还是有一种更优雅的方法?我希望沿着将各个线段的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')

这篇关于根据段长度在ggplot2中颜色geom_segment的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆