Reputation: 1456
I have the following dataframe:
Class Step 1 2 3
TestMe 1 5 10 6
TestMe 2 7 11 5
TestMe 3 9 13 9
TestMe 4 11 15 10
TestMe 5 13 18 4
TestMe 6 15 20 3
TestMe 7 17 23 8
TestMe 8 19 25 11
TestMe 9 21 27 13
TestMe 10 23 30 7
I would like to generate a plot using R such that
Each line in the plot represents a run (i.e., three runs). I tried the following:
dataset <- dataset %>% melt(id.vars = c("Class"))
dataset <- transform(dataset, value = as.numeric(value))
YaxisTitle <- "Fitness"
pp2 <- dataset %>% ggplot(aes(x=variable, y=value, group=Class, colour=Class)) +
geom_line() +
scale_x_discrete(breaks = seq(0, 10, 1)) +
labs(x = as.character(dataset$Class), y = YaxisTitle) +
theme(text = element_text(size=10),legend.position="none")
But I get the following:
How can I fix that?
Upvotes: 1
Views: 90
Reputation: 2609
I went along and made your data reproducible. I am not sure if my answer is exacly what you want, but it seems the most obvious to me from your data.
library(tidyverse)
dataset <- tribble(
~Class, ~Step, ~"1", ~"2", ~"3",
"TestMe", 1, 5, 10, 6,
"TestMe", 2, 7, 11, 5,
"TestMe", 3, 9, 13, 9,
"TestMe", 4, 11, 15, 10,
"TestMe", 5, 13, 18, 4,
"TestMe", 6, 15, 20, 3,
"TestMe", 7, 17, 23, 8,
"TestMe", 8, 19, 25, 11,
"TestMe", 9, 21, 27, 13,
"TestMe", 10, 23, 30, 7,
)
YaxisTitle <- "Fitness"
dataset <- dataset %>%
gather("1", "2", "3", key = "variable", value = "value")
ggplot(dataset, aes(x=Step, y=value, group=variable, colour=variable)) +
geom_line() +
scale_x_discrete(breaks = seq(0, 10, 1)) +
labs(x = as.character(dataset$Class), y = YaxisTitle) +
theme(text = element_text(size=10),legend.position="none")
Upvotes: 2
Reputation: 39154
Your melt
is problematic. Please see the following example for reshaping the data frame and plotting.
library(tidyverse)
dataset <- read.table(text = "Class Step 1 2 3
TestMe 1 5 10 6
TestMe 2 7 11 5
TestMe 3 9 13 9
TestMe 4 11 15 10
TestMe 5 13 18 4
TestMe 6 15 20 3
TestMe 7 17 23 8
TestMe 8 19 25 11
TestMe 9 21 27 13
TestMe 10 23 30 7",
header = TRUE, stringsAsFactors = FALSE)
dataset <- dataset %>%
gather(Variable, Value, starts_with("X"))
YaxisTitle <- "Fitness"
dataset %>%
ggplot(aes(x = Step, y = Value, group = Variable, colour = Variable)) +
geom_line() +
scale_x_discrete(breaks = seq(0, 10, 1)) +
scale_color_manual(values = c("X1" = "Blue", "X2" = "Red", "X3" = "Gold")) +
labs(x = as.character(dataset$Class), y = YaxisTitle) +
theme_minimal() +
theme(text = element_text(size=10),legend.position="none")
Upvotes: 1