Using Factor-Based Plots for Visualization: A Comparative Analysis of Numeric vs Factor Variables.
To modify the code so that it uses a factor variable mapped to the x-axis and still maintains the same appearance, we need to make two changes:
- We add another plot (
p2) where theNsubjects2is used for mapping. - Since there are multiple values in each “bucket”, we don’t want lines to appear on our factor-based plots, so instead we use a boxplot.
Here’s how you could modify your code:
# base plot
p <- ggplot(test_data,
aes(y = Odds, color=EffectSize)) +
facet_wrap(DataType ~ ExpType, labeller = label_both, scales = "free")
# plot with numeric variable mapped to x-axis
p1 <- p + aes(x = Nsubjects) +
geom_line(linewidth = 2) +
geom_ribbon(aes(ymax = Upper, ymin = Lower, fill = EffectSize),
alpha = 0.2)
# plot with factor variable mapped to x-axis (using boxplot)
p2 <- p + aes(x = Nsubjects2) +
geom_boxplot()
# coord layer
cc <- coord_cartesian_panels(
panel_limits = tibble::tribble(
~DataType, ~ExpType, ~ymin, ~ymax
, "A" , "X" , 1, 4
, "A" , "Y" , 1, 6
, "B" , "Y" , 1, 7
)
)
# print plots to show that the same coord layer works for both
p1 + ggtitle("Before (numeric x)")
+ cc + ggtitle("After (numeric x)")
p2 + ggtitle("Before (factor x)")
+ cc + ggtitle("After (factor x)")
This will create two separate plots (p1 and p2) with the same appearance as the base plot, but using a numeric variable mapped to the x-axis in one of them, and a factor variable mapped to the x-axis in the other.
Last modified on 2024-01-29