I made the following plot in R :
library(MASS)
a = rnorm(100, 10, 10)
b = rnorm(100, 10, 5)
c = rnorm(100, 5, 10)
group <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )
d = data.frame(a, b, c, group)
d$group = as.factor(d$group)
parcoord(d[, c(3, 1, 2)], col = 1 + (0:149) %/% 50)
title(main = "Plot", xlab = "Variable", ylab = "Values")
axis(side = 2, at = seq(0, 5, 0.1),
tick = TRUE, las = 1)
Can someone please show me how to color each line in this plot according the value of "d$group" and add a legend in the corner of the screen?
I think the following line of code changes the color of lines per value of "d$group":
parcoord(d[, c(3, 1, 2)], col = d$group)
And this line of code creates a legend:
legend( "topleft", c("A", "B", "C", "D"),
text.col=c("blue", "red", "yellow", "green") )
title("Legend",
cex.main = 1.1)
But I am not sure how to have the colors from the legend match the real colors. I tried:
legend( "topleft", c("A", "B", "C", "D"),
text.col= d$group)
But this did not work. Can someone please show me how to fix this?
Thanks
EDIT: is there a way to run the code (provided in the answer) if variable "C" is a factor?
e.g.
a = rnorm(100, 10, 10)
b = rnorm(100, 10, 5)
c <- sample( LETTERS[1:2], 100, replace=TRUE, prob=c(0.5,0.5) )
group <- sample( LETTERS[1:4], 100, replace=TRUE, prob=c(0.25, 0.25, 0.25, 0.25) )
d = data.frame(a, b, c, group)
d$group = as.factor(d$group)
d$c = as.factor(d$c)
library(tidyverse)
library(ggplot2)
library(dplyr)
d %>%
mutate(rn = row_number()) %>%
pivot_longer(a:c) %>%
ggplot(aes(name, value, group = rn, color = group)) +
scale_x_discrete(expand = expansion(0, 0)) +
geom_line()
question from:
https://stackoverflow.com/questions/65839197/r-changing-plot-colors