Reputation: 45
So basically, I would like to use ggplot function geom_line + geom_point to create the same plots but with fancier graphics.
> a
V1 V2 V3
1 0.8224887 0.7882316 0.7596440
2 0.7892779 0.7604186 0.7409430
3 0.8254516 0.8257800 0.8014778
4 0.8268519 0.7887464 0.7887322
5 0.8226651 0.7981079 0.7934783
plot(6:10, a$V1, type="l", xlab="Folds", ylab="Accuracy", col="Blue",ylim=c(0.7,0.9))
par(new=TRUE)
plot(6:10, a$V2, type="l", xlab="Folds", ylab="Accuracy", col="Orange",ylim=c(0.7,0.9))
par(new=TRUE)
plot(6:10, a$V3, type="l", xlab="Folds", ylab="Accuracy", col="Green",ylim=c(0.7,0.9))
My main goal is to get a legend that helps to distinguish each variable.
I tried to plot just the first line:
ggplot(data = a)+
theme_classic()+
geom_line(aes(x=6:10, y = a$V1, color = "blue"))
The problem is that i don't even get the color I want.
Thanks for reading and helping!
Upvotes: 0
Views: 137
Reputation: 12461
library(tidyverse)
originalData <- tibble(
V1=c(0.8224887, 0.7892779, 0.8254516, 0.8268519, 0.8226651),
V2=c(0.7882316, 0.7604186, 0.8257800, 0.7887464, 0.7981079),
V3=c(0.7596440, 0.7409430, 0.8014778, 0.7887322, 0.7934783)
)
# ggplot works best if your data is 'tidy'
tidyData <- originalData %>%
pivot_longer(cols=c(V1, V2, V3), names_to="Variable") %>%
add_column(X=rep(6:10, each=3))
tidyData
tidyData %>%
ggplot(aes(x=X, y=value, colour=Variable)) +
geom_line() +
theme_classic()
Giving
You can customise your plot from here as you like.
Upvotes: 1
Reputation: 886
library (dplyr)
library (ggplot2)
a <- data.frame(
V1=rnorm(5),
V2=rnorm(5),
V3=rnorm(5),
Folds = 6:10) # make some example data
a %>%
tidyr::gather(key,value,-Folds) %>% #get data in long format for ggplot
ggplot(.,aes(x = Folds,y = value,y,col = key))+
geom_line() + # add line
geom_point() + # add points
scale_color_manual("My Variables",values = c("blue","orange","green")) + #change colours
theme_classic()
Upvotes: 2