首頁  >  文章  >  後端開發  >  如何使用 Matplotlib 在分組長條圖中正確對齊條形並新增註解?

如何使用 Matplotlib 在分組長條圖中正確對齊條形並新增註解?

Barbara Streisand
Barbara Streisand原創
2024-10-26 14:57:03651瀏覽

How to Correctly Align Bars and Add Annotations in a Grouped Bar Chart with Matplotlib?

繪製和註釋分組條形圖

本指南解決了在 matplotlib 中建立分組條形圖時常見的問題。提供的代碼旨在可視化受訪者對各種數據科學領域的興趣,並用條形代表他們的興趣程度(非常感興趣、有點感興趣、不感興趣)。

問題分析

所提供程式碼中的問題在於條形寬度的計算。代碼設定 w=0.8,而不考慮圖中的條形數量。要正確對齊條形,應將 w 除以條形數量。

解決方案

要解決此問題,請調整條形寬度計算以考慮條形數量圖中的條形圖。更有效的方法是使用 pandas.DataFrame.plot 方法產生註解的繪圖。

使用DataFrame.plot 更新程式碼

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

# Create the DataFrame
file = "https://s3-api.us-geo.objectstorage.softlayer.net/cf-courses-data/CognitiveClass/DV0101EN/labs/coursera/Topic_Survey_Assignment.csv"
df = pd.read_csv(file, index_col=0)

# Calculate percentages
df = df.div(2233)

# Plot the grouped bar chart
ax = df.plot.bar(color=['#5cb85c', '#5bc0de', '#d9534f'], figsize=(20, 8), rot=0, ylabel='Percentage', title="The percentage of the respondents' interest in the different data science Area")

# Add annotations
for p in ax.patches:
    ax.annotate(f'{p.get_height():0.2f}', (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center', xytext=(0, 10), textcoords='offset points')</code>

輸出:

[修正後的條形圖片]

此更新的程式碼會產生正確對齊的分組長條圖,並帶有指示每個條形百分比的註解。

以上是如何使用 Matplotlib 在分組長條圖中正確對齊條形並新增註解?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn