0

I have the following code where I am trying to plot a bar plot in seaborn. (This is a sample data and both x and y variables are continuous variables).

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt


xvar = [1,2,2,3,4,5,6,8]
yvar = [3,6,-4,4,2,0.5,-1,0.5]
year = [2010,2011,2012,2010,2011,2012,2010,2011]

df = pd.DataFrame()
df['xvar'] = xvar
df['yvar']=yvar
df['year']=year
df

sns.set_style('whitegrid')

fig,ax=plt.subplots()
fig.set_size_inches(10,5)
sns.barplot(data=df,x='xvar',y='yvar',hue='year',lw=0,dodge=False)

It results in the following plot: enter image description here

Two questions here:

  1. I want to be able to plot the two bars on 2 side by side and not overlapped the way they are now.
  2. For the x-labels, in the original data, I have alot of them. Is there a way I can set xticks to a specific frequency? for instance, in the chart above only I only want to see 1,3 and 6 for x-labels.

Note: If I set dodge = True then the lines become very thin with the original data.

soom
  • 29
  • 1
  • 7
  • As long as any `yval` has the same `xval` it will be plotted at the same point. If you only want to see some `xvar`, the filter the dataframe then plot (e.g. `df[df.xvar.isin([1, 3, 6])]`) – Trenton McKinney Sep 02 '21 at 02:53
  • so instead of bar plot could I use any other plot that would allow me to plot the two side by side? – soom Sep 02 '21 at 05:50

1 Answers1

0

For the first question, get the patches in the bar chart and modify the width of the target patch. It also shifts the position of the x-axis to represent the alignment. The second question can be done by using slices to set up a list or a manually created list in a specific order.

import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt

xvar = [1,2,2,3,4,5,6,8]
yvar = [3,6,-4,4,2,0.5,-1,0.5]
year = [2010,2011,2012,2010,2011,2012,2010,2011]

df = pd.DataFrame({'xvar':xvar,'yvar':yvar,'year':year})

fig,ax = plt.subplots(figsize=(10,5))
sns.set_style('whitegrid')

g = sns.barplot(data=df, x='xvar', y='yvar', hue='year', lw=0, dodge=False)

for idx,patch in enumerate(ax.patches):
    current_width = patch.get_width()
    current_pos = patch.get_x()
    if idx == 8 or idx == 15:
        patch.set_width(current_width/2)
        if idx == 15:
            patch.set_x(current_pos+(current_width/2))

ax.set_xticklabels([1,'',3,'','',6,''])
plt.show()

enter image description here

r-beginners
  • 31,170
  • 3
  • 14
  • 32