I have a dataframe with 3 columns: one of them is a "groupby" column, the other two are "normal" columns with values. I want to generate a boxplot and a bar chart as well. On the bar chart I want to visualize the number of occurences of each group's element. Let my sample code tell this dataframe in more detailed:
li_str = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten']
df = pd.DataFrame([[i]+j[k] for i,j in {li_str[i]:np.random.randn(j, 2).tolist() for i,j in \
enumerate(np.random.randint(5, 15, len(li_str)))}.items() for k in range(len(j))]
, columns=['A', 'B', 'C'])
So above I generate random number of random values to every element in li_str
and I do it for columns B
and C
.
Then I visualize only a boxplot:
fig, ax = plt.subplots(figsize=(16,6))
p1 = df.boxplot(ax=ax, column='B', by='A', sym='')
Now I visualize the number of elements every group has (so the random numbers I generated above with np.random.randint(5, 15, len(li_str))
code):
fig, ax = plt.subplots(figsize=(16,6))
df_gb = df.groupby('A').count()
p2 = df_gb['B'].plot(ax=ax, kind='bar', figsize=(16,6), colormap='Set2', alpha=0.3)
plt.ylim([0, 20])
And now I want these two in one diagram:
fig, ax = plt.subplots(figsize=(16,6))
ax2 = ax.twinx()
df_gb = df.groupby('A').count()
p1 = df.boxplot(ax=ax, column='B', by='A', sym='')
p2 = df_gb['B'].plot(ax=ax2, kind='bar', figsize=(16,6)
, colormap='Set2', alpha=0.3, secondary_y=True)
plt.ylim([0, 20])
Does anybody know why my boxplot is shifted to right with one x-axis tick? I use Python 3.5.1, pandas 0.17.0, matplotlib 1.4.3
Thank you!!!