R中的风筝图

时间:2020-03-07 20:27:26

标签: r matrix ggplot2 diagram

我正在尝试重新创建一个风筝图,以显示最丰富的大型藻类物种的分布。

我的数据如下:

此处:dput(p2[1:3, 1:5])

structure(c(25.04240506, 24.95759494, 24.04113924, 25.0164557, 
24.9835443, 24.04905063, 25.00379747, 24.99620253, 24.03955696, 
25.01677215, 24.98322785, 24.01740506, 25.00474684, 24.99525316, 
24.03955696), .Dim = c(3L, 5L), .Dimnames = list(c("Sphacelaria tribuloides(O)", 
"Amphiroa rigida (R)", "Stypocaulon scoparium (O)"), c("A1", 
"A2", "A3", "B1", "B2")))

当前输出:

[![这就是我的情节] [1]] [1]

目标:

[![这是我的风筝图应该是的样子] [2]] [2]

我确实不确定我在做什么错以及如何解决它。

非常感谢您预先提供的帮助和指导。非常感谢。

1 个答案:

答案 0 :(得分:0)

注意:我更改示例的值,以便获得更多变化,因为所有值都在24或25之间,这说明了为什么在风筝图中几乎得到水平线。我做到了:

df[1:3,1:5] <- sample(5:25, 15, replace = TRUE)

                           A1 A2 A3 B1 B2
Sphacelaria tribuloides(O)  9 18 20  5 17
Amphiroa rigida (R)         6 18 24 18 18
Stypocaulon scoparium (O)  16 18 16 19  8

要获取风筝图,只需使用kiteChart图中的plotrix函数。

library(plotrix)
kiteChart(df)

enter image description here

我没有找到旋转y标签的方法,因为似乎yaxt = "n"las = 1在此功能上不起作用。因此,我尝试找到一种使用ggplot2的方法。

一种可能的方法是首先对数据框进行整形,并通过归因于其因子格式的级别以数字格式转换y和x轴。 您还需要标准化“值”列:

library(dplyr)
library(tidyr)
DF <- as.data.frame(df) %>% mutate(species = rownames(df)) %>%
  pivot_longer(-species, names_to = "X_var", values_to = "values") %>%
  mutate(species = factor(species, levels = unique(species))) %>%
  mutate(X_var = factor(X_var, levels = unique(X_var))) %>%
  mutate(NewY = as.numeric(species)*2) %>%
  mutate(normval = values / max(values))  %>%
  mutate(NewX = as.numeric(X_var))  

# A tibble: 15 x 6
   species                    X_var values  NewY normval  NewX
   <fct>                      <fct>  <dbl> <dbl>   <dbl> <dbl>
 1 Sphacelaria tribuloides(O) A1         9     2   0.375     1
 2 Sphacelaria tribuloides(O) A2        18     2   0.75      2
 3 Sphacelaria tribuloides(O) A3        20     2   0.833     3
 4 Sphacelaria tribuloides(O) B1         5     2   0.208     4
 5 Sphacelaria tribuloides(O) B2        17     2   0.708     5
 6 Amphiroa rigida (R)        A1         6     4   0.25      1
 7 Amphiroa rigida (R)        A2        18     4   0.75      2
 8 Amphiroa rigida (R)        A3        24     4   1         3
 9 Amphiroa rigida (R)        B1        18     4   0.75      4
10 Amphiroa rigida (R)        B2        18     4   0.75      5
11 Stypocaulon scoparium (O)  A1        16     6   0.667     1
12 Stypocaulon scoparium (O)  A2        18     6   0.75      2
13 Stypocaulon scoparium (O)  A3        16     6   0.667     3
14 Stypocaulon scoparium (O)  B1        19     6   0.792     4
15 Stypocaulon scoparium (O)  B2         8     6   0.333     5

现在,您可以使用geom_ribbon来获取风筝图:

library(ggplot2)
ggplot(DF, aes(x = NewX, fill = species))+
  geom_ribbon(aes(ymin = NewY-normval, ymax = NewY+normval))+
  scale_y_continuous(breaks = unique(DF$NewY), labels = levels(DF$species))+
  scale_x_continuous(breaks = unique(DF$NewX), labels = levels(DF$X_var), name = "")

enter image description here 是您要找的东西吗?