Last active
February 12, 2016 20:58
-
-
Save djhocking/76791ca5a8a8cf57b7dc to your computer and use it in GitHub Desktop.
Trying to make a boxplot with ggplot2 in R where the x-axis in continous but their are paired boxplots for each value of on the x-axis based on another factor
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# ggplot boxplot groups of continuous x | |
### Daniel J. Hocking | |
I am trying to make a boxplot with ggplot2 in R where the x-axis in continous but their are paired boxplots for each value of on the x-axis based on another factor with two possible values. I want to make a plot where boxplots are arranged by number of survey years on the x-axis but paired by spatialTF (2 boxplots for every value of n_years) but n_years are not evenly spaced. | |
This plot gets the paired boxplots correct by year but the years on the x-axis are evenly spaced and don't reflect the actual (continuous) time between years. | |
``` | |
ggplot(df_converged, aes(factor(n_years), mean_N_est)) + | |
geom_boxplot(aes(fill = factor(spatialTF))) + | |
scale_fill_manual(values=c("#F8766D", "#619CFF")) | |
``` | |
This next plot gets the spacing between years correct but only puts 1 boxplot for each year rather than having them paired (one for each of the 2 possible values of spatialTF). | |
``` | |
ggplot(df_converged, aes(n_years, mean_N_est, group = n_years)) + | |
geom_boxplot(aes(fill = factor(spatialTF))) + | |
scale_fill_manual(values=c("#F8766D", "#619CFF")) | |
``` | |
Is there anyway to combine these to make my desired plot? |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
df_converged <- data.frame(n_years = rep(c(1:3, 8), each = 30), mean_N_est = rnorm(120), spatialTF = rep(1:2, times = 60))
df_converged$n_years <- factor(df_converged$n_years, levels = c(1:8))
ggplot(df_converged, aes(factor(n_years), mean_N_est)) +
geom_boxplot(aes(fill = factor(spatialTF))) +
scale_fill_manual(values=c("#F8766D", "#619CFF")) +
scale_x_discrete(limits = levels(df_converged$n_years), drop = FALSE)