Skip to content

Instantly share code, notes, and snippets.

@wmvanvliet
Last active August 28, 2018 12:39
Show Gist options
  • Save wmvanvliet/53aba7bb5ad85741a2dacf9c49624a8b to your computer and use it in GitHub Desktop.
Save wmvanvliet/53aba7bb5ad85741a2dacf9c49624a8b to your computer and use it in GitHub Desktop.
Example of how to plot a swarm plot using seaborn
# encoding: utf-8
# Import required Python modules for this example
import pandas as pd
import seaborn as sb
from matplotlib import pyplot as plt
from matplotlib.ticker import MultipleLocator
# Reading the data
dataframe = pd.read_table('Sensory_measurement.txt', index_col=0)
# This gives us a table in the following form:
#
# Percold Perheat Thcold Thheat Tolcold Tolheat
# Subject
# 8 30.48 34.95 15.32 45.60 6.87 48.23
# 9 28.82 34.62 17.50 43.13 3.90 49.45
# 10 29.48 34.22 26.38 42.47 3.90 51.22
# 11 30.30 33.63 25.62 37.70 3.90 49.50
# 12 30.07 35.03 19.73 46.53 3.90 51.90
# ...
# Create a new figure
fig = plt.figure(figsize=(8, 8))
# Now we can use Seaborn to create the swarm plot.
sb.swarmplot(data=dataframe, ax=plt.gca())
# Tweak the plot a little
plt.ylabel('Temperature (°C)') # Label for the y-axis
plt.xlabel('Measurement') # Label for the x-axis
plt.ylim(3, 55) # Set temperature range to 3--55
# Fine-tune the minor and major tick marks
plt.gca().yaxis.set_minor_locator(MultipleLocator(0.5))
plt.gca().yaxis.set_major_locator(MultipleLocator(5))
# Add vertical gridlines at each minor and major tick
plt.grid(which='minor', axis='y', linestyle='solid', color='black', alpha=0.2)
plt.grid(which='major', axis='y', linestyle='solid', color='black', alpha=0.5)
# Make a horizontal line at 32°C
plt.axhline(32, linewidth=2, color='black')
plt.text(-0.4, 32, '32°C', va='bottom') # Write 32°C next to the line
# Remove some margins
plt.tight_layout()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment