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
I have a dataset called mydat
, where I would like to make the following plot with a diagonal line for ref
. Then for mars
and saturn
, I would like to plot them with different colors and symbols. I can do this using plot
just fine.
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")
I would like to plot this in ggplot
. However, I tried the following but couldn't get the same plot:
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()
CodePudding user response:
Maybe you want something like this:
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()
Output:
CodePudding user response:
You just need to keep ref
as its own column when using melt
(i.e. specify it as one of id.vars
). Then we can use its value for the x-axis in the plot:
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")