如何在matplotlib中的“我的绘图”中添加其他标签?

2024-09-25 14:31:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要像照片上那样的东西

enter image description here

这是我的密码:

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

Tags: import密码dfdatalabelsmatplotlibasplt
1条回答
网友
1楼 · 发布于 2024-09-25 14:31:58

从Matplotlib 3.4.0开始,这可以通过^{}和带标签的压缩容器来实现:

# 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')
  • 标签将与数据框的索引对齐:
    • all_labels中的第一个列表将与列0(Unmarried woman)对齐,并在列之间继续
    • 每个子列表(labels)中的索引0将与数据帧中的索引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()

plot

相关问题 更多 >