How to do a boxplot with individual data points using seaborn

2024/10/18 12:05:24

I have a box plot that I create using the following command:

sns.boxplot(y='points_per_block', x='block', data=data, hue='habit_trial')

So the different colors represent whether the trial was a habit trial or not (0,1). I want to also plot the individual data points, which I tried to achieve using:

sns.stripplot(y='points_per_block', x='block', data=data, hue='habit_trial')

The result was the following

enter image description here

I want the individual points to display over the corresponding box plots. Is there a way to do this without resorting to hacking their positions in some manner? The problem comes from the fact that the separation of data using hue works differently for stripplot and boxplot but I would have thought that these would be easily combinable.

Thanks in advance.

Answer

Seaborn functions working with categorical data usually have a dodge= parameter indicating whether data with different hue should be separated a bit. For a boxplot, dodge defaults to True, as it usually would look bad without dodging. For a stripplot defaults to dodge=False.

The following example also shows how the legend can be updated (matplotlib 3.4 is needed for HandlerTuple):

import seaborn as sns
from matplotlib.legend_handler import HandlerTupletips = sns.load_dataset("tips")
ax = sns.boxplot(data=tips, x="day", y="total_bill",hue="smoker", hue_order=['Yes', 'No'], boxprops={'alpha': 0.4})
sns.stripplot(data=tips, x="day", y="total_bill",hue="smoker", hue_order=['Yes', 'No'], dodge=True, ax=ax)
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles=[(handles[0], handles[2]), (handles[1], handles[3])],labels=['Smoker', 'Non-smoker'],loc='upper left', handlelength=4,handler_map={tuple: HandlerTuple(ndivide=None)})

boxplot and stripplot combined

https://en.xdnf.cn/q/73071.html

Related Q&A

Load QDialog directly from UI-File?

I work with QT Designer and create my GUIs with it. To launch the main program, I use this code:import sys from PyQt4 import uic, QtGui, QtCore from PyQt4.QtGui import * from PyQt4.QtCore import *try:_…

Is there a way to detect if running code is being executed inside a context manager?

As the title states, is there a way to do something like this:def call_back():if called inside context:print("running in context")else:print("called outside context")And this would …

Adding title to the column of subplot below suptitle

Is there a simple way to add in to my original code so that I can add another title to both column of my subplot? for example like somewhere in the pink region shown in the picture below.Someone refer…

Conditional Inheritance based on arguments in Python

Being new to OOP, I wanted to know if there is any way of inheriting one of multiple classes based on how the child class is called in Python. The reason I am trying to do this is because I have multip…

Slice endpoints invisibly truncated

>>> class Potato(object): ... def __getslice__(self, start, stop): ... print start, stop ... >>> sys.maxint 9223372036854775807 >>> x = sys.maxint + 69 >…

Selenium Webdriver with Java vs. Python

Im wondering what the pros and cons are of using Selenium Webdriver with the python bindings versus Java. So far, it seems like going the java route has much better documentation. Other than that, it s…

asyncio - how many coroutines?

I have been struggling for a few days now with a python application where I am expecting to look for a file or files in a folder and iterate through the each file and each record in it and create objec…

Calculating a 3D gradient with unevenly spaced points

I currently have a volume spanned by a few million every unevenly spaced particles and each particle has an attribute (potential, for those who are curious) that I want to calculate the local force (ac…

deleting every nth element from a list in python 2.7

I have been given a task to create a code for. The task is as follows:You are the captain of a sailing vessel and you and your crew havebeen captured by pirates. The pirate captain has all of you stand…

Bradley-Roth Adaptive Thresholding Algorithm - How do I get better performance?

I have the following code for image thresholding, using the Bradley-Roth image thresholding method. from PIL import Image import copy import time def bradley_threshold(image, threshold=75, windowsize=5…