This is not a duplicate of this, or this, or this.
I have a data.table
that looks something like this:
animal_frame
first_and_last animal color
c(1, 2) dog red
c(2, 2) cat red
c(4, 2) dog green
c(3, 1) dog red
c(4, 6) pig green
c(3, 3) cat red
c(4, 2) pig red
animal_frame$num_entry = sample(1:nrow(animal_frame), nrow(animal_frame), replace=FALSE)
gives me an indexing column.
Here, the x-axis is num_entry
and the y-axis is first_and_last
, resulting in two points for every tick on the x-axis. Each of these points is to be connected with a vertical line as per this question:
ggplot(data=animal_frame, aes(x=num_entry, y=first_and_last)) +
geom_line(aes(group=num_entry, color=color)) +
scale_color_manual(values = c("green"="green", "red"="red"))
This works well. Now, I'd like to facet this same plot according to animal
, but I want an indexing column (beginning from 1) for each animal. So, using dplyr
, I run:
animal_frame %<>%
group_by(animal) %>%
mutate(facet_num_entry = sample(1:n(), n(), replace=FALSE)) %>%
ungroup()
Now, I try:
ggplot(data=animal_frame, aes(x=facet_num_entry, y=first_and_last)) +
geom_line(aes(group=facet_num_entry, color=color)) +
scale_color_manual(values = c("green"="green", "red"="red")) +
facet_grid(animal ~ .)
But receive geom_path: Each group consists of only one observation. Do you need to adjust the group aesthetic?
When I look at the data frames, it looks like when I add the num_entry
column, there are two entries for every sampled number (I suspect this comes from the fact that each entry in first_and_last
is a vector. This appropriately gives me two observations to group by—and thus two points to draw a vertical line between.) On the other hand, when I add the facet_num_entry
column, there's only one entry for every sampled number. I think there may be something going on with the collapsing of first_and_last
? But I've been screwing with this for a while and can't figure it out.
Also, if there's an easier way to structure my data such that these vertical lines are possible, feel free to suggest it. I couldn't find anything as easy as making first_and_last
a column of vectors.