Hi, folks
My problems isn't new — I took a look around and saw similar examples here and on StackOverflow. Despite the examples, I have not managed to find my error.
I have three datasets, one of which was wide and I made it longer. I stacked them all to have one "big" data frame. My plan was to use the "big" data frame to plot lines for each type
of data, out of which there are 3. There should be 20 lines for X
and 1 line each for types Y
and Z
. All 20 type X
lines should have the same color. But that's not what happened and I'm not sure how to proceed.
Here's an example that reproduces the error.
# Pkgs
library(tidyr)
#> Warning: package 'tidyr' was built under R version 4.2.3
library(dplyr)
#>
#> Attaching package: 'dplyr'
#> The following objects are masked from 'package:stats':
#>
#> filter, lag
#> The following objects are masked from 'package:base':
#>
#> intersect, setdiff, setequal, union
library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.2.3
# Create data
x = matrix(data = rnorm(200), ncol = 20)
x = data.frame("type" = rep("X", 10), x)
colnames(x) = c("type", paste0(1:20))
y = data.frame("type" = "Y", "ind" = 1:20, "values" = rnorm(20))
z = data.frame("type" = "Z", "ind" = 1:20, "values" = rnorm(20))
# Wrangle x to it's longer
x_lon =
x |>
pivot_longer(cols = -c(type),
names_to = "ind",
values_to = "values")
# Bind all dataframes together
all_df = rbind(x_lon,y,z)
all_df = all_df |> mutate(ind = factor(ind, levels = paste0(1:20)))
all_df |>
ggplot(aes(x = ind, y = values, col = type)) +
geom_line(aes(group = type, col = type)) +
theme_minimal() +
theme(legend.title = element_blank(),
legend.position = "bottom")
All help will be appreciated.