A group of people were asked to what degree they agree or disagree with a statement at two time points.
Our question is how many people changed their minds. Statistically we might use and , but we will be focusing on visualization of the data with .
We first need to re-structure this matrix into a data frame:
What we want to do is mark the cells where people did not change their response - where is equal to - with a different line type. We can do this by adding into the plots aesthetics. This should give diagonal cells a different line-type compared to the other cells. Simple enough, no?
What the hell happened?? The order of cells has changed!
The first thing to understand is that we have some implicit grouping going on. The group aesthetic is by default set to the interaction of all discrete variables in the plot. […] For most applications the grouping is set implicitly by mapping one or more discrete variables to , , , , , , , and/or . From the ggplot2 manual on Aesthetics: grouping This means that our mapping of and has been used to set the ing of the cells. The second thing to understand is the order in which these ing aesthetics are used for grouping: First, the layer-specific aesthetics are used (in our case, , which is in the layer). Then (if , which is the default) any global aesthetics are used (, which is set in the call to ). This is why the order of the cells has changed: Cells were grouped first by the before-after equality, and only then by the type of “after” response.
The fix is easy, we have to make sure the grouping aesthetics are specified in a way that pulls them in the correct order; that is first by “after” and then by the before-after equality. Here are all the ways to do that: We can explicitly set the aesthetic, using the function, but to add insult to injury, this function must be supplied with the grouping variables in the reverse order (unless you set ): ggplot(Agreement_df, aes(Before, Freq, fill = After)) +
geom_col(
position = "fill", width = 0.85,
color = "black", size = 1,
mapping = aes(linetype = Before == After,
group = interaction(Before == After, After)) #