Due to the nature of my data, I have two age groups that have done two sessions of a test. It's important that I get a way to visualize how the full sample behaves (boxplot) and how each individual changes between sessions (Swarmplot/Lineplot).
When not using hues or groups, it's easy to do it by just using consecutively the three functions, or just skipping lineplot, like here (Swarmplot with connected dots); but as I am using hues to separate between groups, I haven't managed to join the data points of each subject Pre and Post.
So far, I have achieved to plot the lines but they are not alligned with the boxplot, but instead they are alligned to the ticks with the "Pre" and "Post" conditions:
Plot below shows four boxplots (pre_young, pre_old, and post_young, post_old), with the data points aligned to each boxplot, but lines aligned to the ticks of "Pre" and "Post", instead to the actual datapoints or middle of the boxplots.
I got that through this code:
fig, ax = plt.subplots(figsize=(7,5))
sns.boxplot(data=test_data,
x="Session",
y="Pre_Post",
hue="Age",
palette="pastel",
boxprops=boxprops,
ax=ax)
sns.swarmplot(data=test_data,
x="Session",
y="Pre_Post",
hue="Age",
dodge=True,
palette="dark",
ax=ax)
sns.lineplot(data=test_data,
x="Session",
y="Pre_Post",
hue="Age",
estimator=None,
units="Subject",
style="Age",
markers=True,
palette="dark",
ax=ax)
plt.title("Test")
plt.xlabel("Session")
plt.ylabel("Score")
# Move the legend outside the plot
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
plt.show()
I have also tried to get the coordinates of the points through:
points = ax.collections[0]
offsets = points.get_offsets()
x_coords = offsets[:, 0]
y_coords = offsets[:, 1]
But I couldn't manage to correlate each coordinate to the subject that they are related to.
I am adding a sample of my dataset if it helps you to help me. It is in csv format:
'Session,Subject,Age,Pre_Post\nPre,SY01,young,14.0\nPre,SY02,young,14.0\nPre,SY03,young,13.0\nPre,SY04,young,13.0\nPre,SY05,young,13.0\nPre,SY06,young,15.0\nPre,SY07,young,14.0\nPre,SY08,young,14.0\nPre,SA01,old,5.0\nPre,SA02,old,1.0\nPre,SA03,old,10.0\nPre,SA04,old,3.0\nPre,SA05,old,9.0\nPre,SA06,old,5.0\nPre,SA07,old,13.0\nPre,SA08,old,13.0\nPost,SY01,young,14.0\nPost,SY02,young,13.0\nPost,SY03,young,14.0\nPost,SY04,young,13.0\nPost,SY05,young,15.0\nPost,SY06,young,13.0\nPost,SY07,young,15.0\nPost,SY08,young,14.0\nPost,SA01,old,6.0\nPost,SA02,old,2.0\nPost,SA03,old,10.0\nPost,SA04,old,7.0\nPost,SA05,old,8.0\nPost,SA06,old,11.0\nPost,SA07,old,14.0\nPost,SA08,old,11.0\n'