Reputation: 757
I have been struggling with a plot for sometimes
df<- structure(list(x = c("1", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "11", "12", "1", "2", "3", "4", "5", "6", "7", "8",
"9", "10", "11", "12"), variable = structure(c(1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 2L), .Label = c("my_rep1a", "you_rep2a"), class = "factor"),
value = c(-7.70891, 0.9699727, 3.644688, 2.810303, -4.579114,
-6.57653, -1.938455, 3.201102, 4.951608, -1.263285, -0.9699727,
3.675765, -2.269753, -1.255846, 1.336035, -0.7997434, -0.4488655,
0.4488655, 0.7199451, 2.504063, 0.7398947, 0.6827841, -3.841076,
-3.018841)), row.names = c(NA, -24L), class = "data.frame")
SO I plot it like this
ggplot(data = df, aes(x = x, y = value,
group = variable, color = variable)) + geom_line()
it does not give me the right order in x axis
I did try to change my x to character as df$x <- as.character(df$x)
but did not help . The same when I convert it to integer
if I use integer or numeric, it gives me different numbers in x axis which I cannot know if it plots it correctly or not
Upvotes: 2
Views: 561
Reputation: 76663
One way is to get acquainted with package stringr
, function str_sort
. Set argument numeric = TRUE
to sort characters numerically.
lvls <- stringr::str_sort(unique(df$x), numeric = TRUE)
df$x <- factor(df$x, levels = lvls)
ggplot(data = df, aes(x = x, y = value,
group = variable, color = variable)) +
geom_line()
Upvotes: 2