R:如何以不同的方式绘制 ggplot colored/shaped 点

R: how to ggplot differently colored/shaped points

set.seed(3)
mydat <- data.frame(ref = rnorm(5), mars = rnorm(5), saturn = rnorm(5), time = c(0, 0.5, 1, 1.5, 2))
> mydat
         ref        mars     saturn time
1  0.9006247  0.70551551  0.7865069  0.0
2  0.8517704  1.30035799 -0.3104631  0.5
3  0.7277152  0.03825201  1.6988848  1.0
4  0.7365021 -0.97928377 -0.7945937  1.5
5 -0.3521296  0.79376123  0.3484377  2.0

我有一个名为 mydat 的数据集,我想在其中绘制以下带有 ref 对角线的图。然后对于 marssaturn,我想用不同的颜色和符号绘制它们。我可以使用 plot 来做到这一点。

plot(mydat$ref, mydat$ref, type = "l",
     xlab = "Reference", ylab = "Actual measurement", ylim = c(-1, 2))
points(mydat$ref, mydat$mars, pch = 15, col = "blue")
points(mydat$ref, mydat$saturn, pch = 18, col = "green")

我想在 ggplot 中绘制它。然而,我尝试了以下但无法得到相同的情节:

library(ggplot2)
library(reshape2)
melt_mydat <- reshape2::melt(mydat, id.vars = "time")
ggplot(data = melt_mydat, mapping = aes(x = value, y = value, color = as.factor(variable), group = as.factor(variable))) +  geom_point()

也许你想要这样的东西:

library(ggplot2)
ggplot(mydat, aes(x = ref)) +
  geom_point(aes(y = mars), color = "blue") +
  geom_point(aes(y = saturn), color = "green") +
  geom_line(aes(y = ref)) +
  labs(x = "Reference", y = "Actual measurement") +
  theme_minimal()

输出:

您只需要在使用 melt 时将 ref 保留为它自己的列(即将其指定为 id.vars 之一)。然后我们可以将其值用于图中的 x-axis:

set.seed(3)
mydat <- data.frame(ref = rnorm(5), mars = rnorm(5), saturn = rnorm(5), time = c(0, 0.5, 1, 1.5, 2))

library(ggplot2)
library(reshape2)
melt_mydat <- reshape2::melt(mydat, id.vars = c("time","ref"))

ggplot(data = melt_mydat, aes(x = ref, y = value, color = variable)) +
  geom_point() +
  geom_abline(slope = 1) +
  scale_color_manual(values = c("blue", "green")) +
  labs(x = "Reference", y = "Actual measurement")