我有一个包含 3 列的数据框:其中一列是“groupby”列,另外两列是带有值的“普通”列。我还想生成箱线图和条形图。在条形图上,我想可视化每个组元素出现的次数。让我的示例代码更详细地告诉这个数据框:
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'])
所以上面我为每个元素生成随机数的随机值li_str
我为专栏做这件事B
and C
.
然后我只可视化一个箱线图:
fig, ax = plt.subplots(figsize=(16,6))
p1 = df.boxplot(ax=ax, column='B', by='A', sym='')
My result is:
现在我可视化每个组的元素数量(因此我上面生成的随机数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:
现在我想要将这两个图合而为一:
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:
有谁知道为什么我的箱线图向右移动一个 x 轴刻度?我使用Python 3.5.1,pandas 0.17.0,matplotlib 1.4.3
谢谢你!!!