【问题标题】:How to add additional labels in my plot in matplotlib? [duplicate]如何在 matplotlib 的图中添加其他标签? [复制]
【发布时间】:2021-09-09 12:37:00
【问题描述】:

我想要图片上的东西

这是我的代码:

import matplotlib.pyplot as plt
import pandas as pd

plt.style.use('seaborn-notebook')

data = {
    'Unmarried woman': [36, 23, 28, 20, 16],
    'Married woman': [26, 38, 49, 14, 38]
}

unmarried_labels = ['30–55', '14–50', '16-59', '16-24', '13-26']
married_labels = ['25–50', '29–59', '34–89', '11–18', '33–55']

df = pd.DataFrame(data, columns=['Unmarried woman', 'Married woman'],
                  index=['Africa', 'Asia', 'Latin America', 'Northern America',
                         'Europe'])

df.plot.barh()

plt.title(
    'Abortion rate per 1000 women aged 15–44 y. by marital status (2010–2014)',
    fontweight='bold', fontsize=11)

plt.show() 

【问题讨论】:

    标签: python matplotlib plot


    【解决方案1】:

    从 Matplotlib 3.4.0 开始,这可以通过 bar_labels 和带有标签的压缩容器来完成:

    # Save axes returned from DataFrame plot
    ax = df.plot.barh()
    # Iterate over containers and all_labels together
    for container, labels in zip(ax.containers, all_labels):
        ax.bar_label(container, labels=labels, label_type='center')
    
    • 标签将与 DataFrame 的索引对齐:
      • all_labels 中的第一个列表将与第 0 列 (Unmarried woman) 对齐并继续跨列
      • 每个子列表 (labels) 中的索引 0 将与 DataFrame 中的索引 0 对齐,即Africa 并继续向下行。

    齐心协力:

    import matplotlib.pyplot as plt
    import pandas as pd
    
    plt.style.use('seaborn-notebook')
    
    unmarried_labels = ['30–55', '14–50', '16-59', '16-24', '13-26']
    married_labels = ['25–50', '29–59', '34–89', '11–18', '33–55']
    all_labels = [unmarried_labels, married_labels]
    
    df = pd.DataFrame({'Unmarried woman': [36, 23, 28, 20, 16],
                       'Married woman': [26, 38, 49, 14, 38]},
                      columns=['Unmarried woman', 'Married woman'],
                      index=['Africa', 'Asia', 'Latin America', 'Northern America',
                             'Europe'])
    
    # Save axes returned from DataFrame plot
    ax = df.plot.barh()
    # Iterate over containers and all_labels together
    for container, labels in zip(ax.containers, all_labels):
        ax.bar_label(container, labels=labels, label_type='center')
    
    plt.title(
        'Abortion rate per 1000 women aged 15–44 y. by marital status (2010–2014)',
        fontweight='bold',
        fontsize=11
    )
    
    plt.tight_layout()
    plt.show()
    

    【讨论】:

    • 不客气。我不确定标签的顺序。我把标签放在正确的地方了吗?
    • 顺序颠倒了,但问题不大
    • 我不确定标签在欧洲是否有married_labels[0],这对我来说意味着'25–50',但我认为您的标签顺序正确。无论如何,我已经更新了我的答案以反映正确的顺序。
    猜你喜欢
    • 2020-12-13
    • 1970-01-01
    • 2014-06-22
    • 2013-10-11
    相关资源
    最近更新 更多