Reputation: 27
I am creating scatterplots in R using ggplot2 to visualize populations over time. My data set looks like the following:
sampling_period cage total_1 total_2 total_3
4 y 34 95 12
4 n 89 12 13
5 n 23 10 2
I have been making individual scatterplots for the variables total_1, total_2, and total_3 with the following code:
qplot(data=BLPcaged, x=sampling_period, y=total_1, color=cage_or_control)
qplot(data=BLPcaged, x=sampling_period, y=total_2, color=cage_or_control)
qplot(data=BLPcaged, x=sampling_period, y=total_3, color=cage_or_control)
I want to create a scatterplot that contains the information about all three populations over time. I want the final product to be composed of three scatterplots one on top of each other and have the same scale for the axes. This way I could compare all three populations in one visualization.
I know that I can use facet to make different plots for the levels of a factor, but can it also be used to create different plots for different variables?
Upvotes: 1
Views: 437
Reputation: 4282
You can use melt()
to reshape your data with total
as a factor that you can facet on:
BLPcaged = data.frame(sampling_period=c(4,4,5),
cage=c('y','n','n'),
total_1=c(34,89,23),
total_2=c(95,12,10),
total_3=c(12,13,2))
library(reshape2)
BLPcaged.melted = melt(BLPcaged,
id.vars=c('sampling_period','cage'),
variable.name='total')
So now BLPcaged.melted
looks like this:
sampling_period cage total value
1 4 y total_1 34
2 4 n total_1 89
3 5 n total_1 23
4 4 y total_2 95
5 4 n total_2 12
6 5 n total_2 10
7 4 y total_3 12
8 4 n total_3 13
9 5 n total_3 2
You can then facet this by total
:
ggplot(BLPcaged.melted, aes(sampling_period, value, color=cage)) +
geom_point() +
facet_grid(total~.)
Upvotes: 1