首页  >  文章  >  后端开发  >  如何使用 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