R根据行属性创建列散点图(ggplot)

时间:2020-08-31 08:52:21

标签: r ggplot2 scatter

我有以下类型的表:

df0 <- read.table(text = 'Sample Method     Mg  Al  Ca  Ti 
Sa  A   5.5 2.2 33  0.2
Sb  A   4.2 1.2 44  0.1
Sc  A   1.1 0.5 25  0.3
Sd  A   3.3 1.3 31  0.5
Se  A   6.2 0.2 55  0.6
Sa  B   5.2 2   35  0.25
Sb  B   4.6 1.3 48  0.1
Sc  B   1.6 0.8 22  0.32
Sd  B   3.1 1.6 29  0.4
Se  B   6.8 0.3 51  0.7
Sa  C   5.6 2.5 30  0.2
Sb  C   4.1 1.2 41  0.15
Sc  C   1   0.6 22  0.4
Sd  C   3.2 1.5 30  0.5
Se  C   6.8 0.1 51  0.65', header = T, stringsAsFactors = F)

其中包括化学成分。我想将方法​​A用作参考(X轴),并使用Y中的方法B,C的数据(具有线性趋势)自动绘制散点图。基准线为1:1时,这将完美匹配。

换句话说,我想生成这样的图:

Scatter plots of A versus B or C, with the reference line 1:1

我认为解决方案可以从将数据帧转换为:

df <- read.table(text = 'Sample     Mg_A    Al_A    Ca_A    Ti_A    Mg_B    Al_B    Ca_B    Ti_B    Mg_C    Al_C    Ca_C    Ti_C
Sa  5.5 2.2 33  0.2 5.2 2   35  0.25    5.6 2.5 30  0.2
Sb  4.2 1.2 44  0.1 4.6 1.3 48  0.1 4.1 1.2 41  0.15
Sc  1.1 0.5 25  0.3 1.6 0.8 22  0.32    1   0.6 22  0.4
Sd  3.3 1.3 31  0.5 3.1 1.6 29  0.4 3.2 1.5 30  0.5
Se  6.2 0.2 55  0.6 6.8 0.3 51  0.7 6.8 0.1 51  0.65
', header = T, stringsAsFactors = F)

但是我不知道该怎么走。

任何帮助将不胜感激。 最好,安妮·克里斯汀(Anne-Christine)

1 个答案:

答案 0 :(得分:2)

您可以使用以下代码

library(tidyverse)

df0 %>%
  pivot_wider(names_from = Method, values_from = c(Mg, Al, Ca, Ti)) %>% 
  pivot_longer(cols = -Sample) %>% #wide to long data format
  separate(name, c("key","number"), sep = "_") %>%  
  group_by(number) %>% #Group the vaules according to number
  mutate(row = row_number()) %>% #For creating unique IDs 
  pivot_wider(names_from = number, values_from = value) %>%
  ggplot() +
  geom_point(aes(x=A, y=B, color = "A vs B")) + 
  geom_point(aes(x=A, y=C, color = "A vs C")) +
  geom_abline(slope=1, intercept=0) +
  geom_smooth(aes(x=A, y=B, color = "A vs B"), method=lm, se=FALSE, fullrange=TRUE)+
  geom_smooth(aes(x=A, y=C, color = "A vs C"), method=lm, se=FALSE, fullrange=TRUE)+
  facet_wrap(key~., scales = "free")+
  theme_bw()+
  ylab("B or C") +
  xlab("A")

enter image description here

数据

df0 = structure(list(Sample = c("Sa", "Sb", "Sc", "Sd", "Se", "Sa", 
"Sb", "Sc", "Sd", "Se", "Sa", "Sb", "Sc", "Sd", "Se"), Method = c("A", 
"A", "A", "A", "A", "B", "B", "B", "B", "B", "C", "C", "C", "C", 
"C"), Mg = c(5.5, 4.2, 1.1, 3.3, 6.2, 5.2, 4.6, 1.6, 3.1, 6.8, 
5.6, 4.1, 1, 3.2, 6.8), Al = c(2.2, 1.2, 0.5, 1.3, 0.2, 2, 1.3, 
0.8, 1.6, 0.3, 2.5, 1.2, 0.6, 1.5, 0.1), Ca = c(33L, 44L, 25L, 
31L, 55L, 35L, 48L, 22L, 29L, 51L, 30L, 41L, 22L, 30L, 51L), 
    Ti = c(0.2, 0.1, 0.3, 0.5, 0.6, 0.25, 0.1, 0.32, 0.4, 0.7, 
    0.2, 0.15, 0.4, 0.5, 0.65)), class = "data.frame", row.names = c(NA, 
-15L))