首页 文章

绘制两个数据帧值计算X轴标签的问题

提问于
浏览
0

我绘制了两个不同数据帧的值计数,但第二个数据帧是使用错误的x轴标签自动绘制的 . (参见照片)有没有办法改变每个图中条形的顺序,或者使图形上的所有图形都与x轴标签对齐?现在,它们只是按降序排序,但我需要它们根据x轴标签进行排序 .

在“df”数据框中,他们是158名女性和140名男性 . 在我的“签名”数据框中,有13名女性和19名男性 . 当我绘制这些图时,该图显示140/13女性和158/19男性,当它应显示158/13女性和140/19男性 . 我已经能够使用value_counts方法中的“ascending”参数来反转值计数的顺序,但是此解决方案不适用于具有两个以上不同值的数据框 .

结果情节:
plot

> df['Gender'].value_counts()

F    158
M    140
Name: Gender, dtype: int64

> signed['Gender'].value_counts()

M    19
F    13
Name: Gender, dtype: int64

df['Gender'].value_counts().plot('bar', position=1, width = width)
signed['Gender'].value_counts().plot('bar', color='skyblue', position=0, width = width)
width = .25
plt.show()

(见上图的照片)

2 回答

  • 0

    在value_counts()之后使用sort_index()

    width = .25    
    df['Gender'].value_counts().sort_index().plot('bar', position=1, width = width)
    signed['Gender'].value_counts().sort_index().plot('bar', color='skyblue', position=0, width = width)
    plt.show()
    
  • 0

    考虑通过加入性别指数的两个系列来合并到单个数据框中:

    import matplotlib
    matplotlib.style.use('ggplot')
    
    ...
    graph_df = df['Gender'].value_counts().rename('df').to_frame()\
                   .join(signed['Gender'].value_counts().rename('signed').to_frame())
    
    graph_df.plot(kind='bar',figsize=(8, 4))
    

    Plot Output

相关问题