python y轴不均匀,python熊猫绘制两个y轴的偏移x轴

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 Band C.

Then I visualize only a boxplot:

fig, ax = plt.subplots(figsize=(16,6))

p1 = df.boxplot(ax=ax, column='B', by='A', sym='')

My result is:

dc1345fdf80c40ed77af4ed7e987851f.png

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])

My result is:

4147014f22dee07b0b53497b317f1765.png

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])

My result is:

ac1e0f8dd9a145362ad93b479c161215.png

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!!!

解决方案

It's because the boxplot and the bar plot do not use the same xticks even if the labels are the same.

df.boxplot(column='B', by='A')

plt.xticks()

(array([ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]), )

df.groupby('A').count()['B'].plot(kind='bar')

plt.xticks()

(array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]), )

At a glance it looks to me like an inconsistency which should be fixed in matplotlib boxplot(), but I might just be overlooking the rationale.

As a workaround use matplotlib bar(), that allows you to specify the xticks to match those of the boxplot (I did not found a way to do it with df.plot(kind='bar').

df.boxplot(column='B', by='A')

plt.twinx()

plt.bar(left=plt.xticks()[0], height=df.groupby('A').count()['B'],

align='center', alpha=0.3)

nYXDf.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值