I having been trying for ages to plot this data the way I want on seaborn, from a pandas dataframe. Any advice would be appreciated.
The Data is in a dataframe and looks like this, with 12 months, and 11 columns plus a month column:
Month FSRPX1M VOX1M XLB1M ... XLP1M XLU1M XLV1M XLY1M
0 Jan 0.087643 -0.561428 -0.409286 ... -0.177143 0.232858 0.521428 0.457857
1 Feb 0.132429 -0.265715 0.470715 ... 0.067142 -0.479286 -0.177143 0.363571
2 Mar 0.152429 1.002142 0.437857 ... 0.588573 0.671428 0.055000 0.727856
3 Apr 0.150071 2.445000 1.331428 ... 0.551428 1.100715 0.790715 2.175714
4 May -0.089429 -0.115714 0.275000 ... 0.240000 0.113572 0.650716 -0.366429
What I want to do is plot a swarm plot, with Months along the X Axis, and the number along the Y axis, with 11 'dots' for each month, representing the 11 columns, with an associated a color coded key.
I have tried various things including [where df is the dataframe and val_list is a list of the columns I want as dots]:
sns.swarmplot(data = df, x=df['Month'], y = df[val_list])
and
sns.swarmplot(data = df, x=df['Month'], hue = df[val_list])
as well as trying to slice the dataframe, and make a plot, one column at a time using a for loop:
for e in val_list:
sns.stripplot(data = df, x=df['Month'], y = df[e])
Any help and explanation of what I'm doing wrong would be great, thanks
The last one makes a plot, but all the dots are the same color and unlabelled
To work with hue
, Seaborn needs the data in "long form" . Pandas' melt
can be used to convert a "wide" dataframe to a "long" one. The Set3
colormap has 12 colors (the default tab10
only has 10).
from matplotlib import pyplot as plt
import seaborn as sns
import pandas as pd
import numpy as np
elements = ['Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron', 'Carbon',
'Nitrogen', 'Oxygen', 'Fluorine', 'Neon', 'Sodium']
df = pd.DataFrame(np.random.randn(12, len(elements)), columns=elements)
df['Month'] = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
df_long = df.melt(id_vars='Month', var_name='Element', value_name='Value')
ax = sns.swarmplot(data=df_long, x='Month', y='Value', hue='Element', palette='Set3')
ax.legend(bbox_to_anchor=(1.01, 1.02), loc='upper left', title='Element')
plt.tight_layout()
plt.show()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.