각 막대에 대해 여러 값을 사용하여 Matplotlib의 그룹화된 막대 차트에 주석을 추가하는 방법은 무엇입니까?

Mary-Kate Olsen
풀어 주다: 2024-10-27 10:24:30
원래의
649명이 탐색했습니다.

How to annotate a grouped bar chart in Matplotlib with multiple values for each bar?

그룹화된 막대 차트에 대한 여러 주석

문제:
Matplotlib를 사용하여 그룹화된 막대 차트를 생성하려고 하면 출력이 올바르지 않게 나타납니다. .

코드 예:

<code class="python">import matplotlib.pyplot as plt

# sample data
labels = ['Label 1', 'Label 2', 'Label 3']
data1 = [5, 10, 15]
data2 = [15, 10, 5]

# create the bar chart
plt.bar(labels, data1, 0.4, label='Data Set 1')
plt.bar(labels, data2, 0.4, label='Data Set 2', bottom=data1)

# attempt to annotate each bar
for i in range(3):
    plt.annotate(data1[i], (labels[i], data1[i]), xytext=(-5, 5), textcoords='offset points')
    plt.annotate(data2[i], (labels[i], data2[i]+data1[i]), xytext=(-5, 5), textcoords='offset points')

plt.legend()
plt.show()</code>
로그인 후 복사

예상 출력:

각 막대에는 해당 값으로 주석이 추가되어야 합니다.

해결 방법:

방법 1: bar_label 사용

<code class="python">import matplotlib.pyplot as plt

plt.bar(labels, data1, 0.4, label='Data Set 1')
plt.bar(labels, data2, 0.4, label='Data Set 2', bottom=data1)

for i in range(3):
    plt.bar_label(plt.gca().containers[i], labels=(data1[i], data2[i]), fmt='%.1f', padding=10)

plt.legend()
plt.show()</code>
로그인 후 복사

방법 2: 주석 사용

<code class="python">import matplotlib.pyplot as plt

plt.bar(labels, data1, 0.4, label='Data Set 1')
plt.bar(labels, data2, 0.4, label='Data Set 2', bottom=data1)

for i in range(3):
    height1 = data1[i]
    height2 = data2[i]

    # annotate for data set 1
    plt.annotate(str(height1), (labels[i], height1), xytext=(0, 5), textcoords='offset points')

    # annotate for data set 2
    plt.annotate(str(height2), (labels[i], height1 + height2), xytext=(0, 5), textcoords='offset points')

plt.legend()
plt.show()
````
</code>
로그인 후 복사

위 내용은 각 막대에 대해 여러 값을 사용하여 Matplotlib의 그룹화된 막대 차트에 주석을 추가하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!