gpt4 book ai didi

r - 如何使用 R 或 ggplot2 绘制六边形散点图?

转载 作者:行者123 更新时间:2023-12-04 12:09:49 30 4
gpt4 key购买 nike

测试数据:

set.seed(123)
Data <- data.frame(Pro=rnorm(20), Cla=rnorm(20), Neu=rnorm(20))

我想将每个样本(行)绘制为六边形中的点(上图)。点的位置基于三个坐标,彼此之间有 120 度角(下图)。

enter image description here

(图来自 Anoop P. Patel et al. Science,2014 年)

最佳答案

我不知道自动执行此操作的任何特定方法,但您可以使用一些三角函数来计算正确的坐标。

请参阅下面的解决方案

set.seed(123)
Data <- data.frame(Pro=rnorm(20), Cla=rnorm(20), Neu=rnorm(20))

library(tidyverse)
#> Loading tidyverse: ggplot2
#> Loading tidyverse: tibble
#> Loading tidyverse: tidyr
#> Loading tidyverse: readr
#> Loading tidyverse: purrr
#> Loading tidyverse: dplyr
#> Warning: package 'dplyr' was built under R version 3.4.2
#> Conflicts with tidy packages ----------------------------------------------
#> filter(): dplyr, stats
#> lag(): dplyr, stats
Data %>%
# Separating the S1, S2 and S3 axes into their x-y components is done using simple trigonometry.
# S1 is the trivial case as it only has y component.
# S2 and S3 are both 30 degrees (pi/6 radians) below the x-axis
mutate(S1_x = Pro*cos(pi/2), S1_y = Pro*sin(pi/2), # Deconvolve S1 axis into cartesian coordinates (x,y)
S2_x = Cla*cos(pi/6), S2_y = -Cla*sin(pi/6), # Deconvolve S2 axis into cartesian coordinates (x,y)
S3_x = -Neu*cos(pi/6), S3_y = -Neu*sin(pi/6)) %>% # Deconvolve S3 axis into cartesian coordinates (x,y)
mutate(x = S1_x + S2_x + S3_x, y = S1_y + S2_y + S3_y) %>% # Combine x and y compononts from S1, S2 and S3
ggplot(aes(x = x, y=y))+geom_point()

coordinates plotted

# Just to prove that the maths works, plot the hexagon described by unit length
path <- data.frame(Pro = c(1,1,0,0,0,1,1), Cla = c(0,1,1,1,0,0,0), Neu = c(0,0,0,1,1,1,0))
path %>%
mutate(S1_x = Pro*cos(pi/2), S1_y = Pro*sin(pi/2),
S2_x = Cla*cos(pi/6), S2_y = -Cla*sin(pi/6),
S3_x = -Neu*cos(pi/6), S3_y = -Neu*sin(pi/6)) %>%
mutate(x = S1_x + S2_x + S3_x, y = S1_y + S2_y + S3_y) %>%
ggplot(aes(x = x, y=y))+geom_path()

outer hexagon plotted

关于r - 如何使用 R 或 ggplot2 绘制六边形散点图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47038217/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com