I am new in data visualization. I am practicing Seaborn and I am trying to plot a barplot with this dataframe. I want the chart has 3 bars on each symbol, however, the output has only 1 bar on each symbol. May I know how to fix it?
Part of the DataFrame…
JavaScript
x
8
1
returns_7d returns_30d returns_ytd
2
symbol
3
TDOC -0.210839 -17.712095 -3.922423
4
EXAS -4.649067 -6.439275 -1.415680
5
PACB -2.953760 11.886232 37.815711
6
REGN 0.465364 5.803325 -0.629814
7
TWST 6.707956 3.619967 10.4043
8
The code like this:
JavaScript
1
21
21
1
import matplotlib.pyplot as plt
2
%matplotlib inline
3
import seaborn as sns
4
5
# Change the style of the figure to the "dark" theme
6
sns.set_style("darkgrid")
7
8
plt.figure(figsize=(12,6))
9
plt.title('YTD Returns')
10
11
sns.barplot(x=returns_all.index,y=returns_all['returns_7d'],color='b',edgecolor='w',label='returns_7d')
12
sns.barplot(x=returns_all.index,y=returns_all['returns_30d'],color='r',edgecolor='w',label='returns_30d')
13
sns.barplot(x=returns_all.index,y=returns_all['returns_ytd'],color='g',edgecolor='w',label='returns_ytd')
14
15
16
plt.xlabel('symbol', fontsize=11)
17
plt.ylabel('%', fontsize=11)
18
plt.xticks(rotation = 90)
19
plt.legend()
20
plt.show()
21
Output like this:
Advertisement
Answer
To create such a plot using seaborn, note that seaborn prefers its data in “long form”. reset_index
converts the index to a regular column, and melt
converts the columns to <variable, value>
pairs.
JavaScript
1
18
18
1
import matplotlib.pyplot as plt
2
import seaborn as sns
3
import pandas as pd
4
from io import StringIO
5
6
data_str = ''' returns_7d returns_30d returns_ytd
7
TDOC -0.210839 -17.712095 -3.922423
8
EXAS -4.649067 -6.439275 -1.415680
9
PACB -2.953760 11.886232 37.815711
10
REGN 0.465364 5.803325 -0.629814
11
TWST 6.707956 3.619967 10.4043'''
12
df = pd.read_csv(StringIO(data_str), delim_whitespace=True)
13
df.index.name = 'symbol'
14
df_long = df.reset_index().melt(id_vars='symbol')
15
16
sns.barplot(data=df_long, x='symbol', y='value', hue='variable', palette='rocket')
17
plt.show()
18
The long dataframe looks like:
JavaScript
1
17
17
1
symbol variable value
2
0 TDOC returns_7d -0.210839
3
1 EXAS returns_7d -4.649067
4
2 PACB returns_7d -2.953760
5
3 REGN returns_7d 0.465364
6
4 TWST returns_7d 6.707956
7
5 TDOC returns_30d -17.712095
8
6 EXAS returns_30d -6.439275
9
7 PACB returns_30d 11.886232
10
8 REGN returns_30d 5.803325
11
9 TWST returns_30d 3.619967
12
10 TDOC returns_ytd -3.922423
13
11 EXAS returns_ytd -1.415680
14
12 PACB returns_ytd 37.815711
15
13 REGN returns_ytd -0.629814
16
14 TWST returns_ytd 10.404300
17