【问题标题】:Error while displaying percentages while plotting bar graph in dataframes在数据框中绘制条形图时显示百分比时出错
【发布时间】:2020-09-20 15:35:47
【问题描述】:

我试图显示每列的百分比并遇到错误--IndexError: index 3 is out of bounds for axis 0 with size 3

import pandas as pd
import numpy as np 
import matplotlib.pyplot as plt
% matplotlib inline 
import seaborn as sns


df = pd.read_csv('https://github.com/Kevin-ck1/Intro-To-Data-Science/raw/master/hotel_bookings.csv')

df_booking = df.copy()

df_booking['percentage'] = round(df_booking['arrival_date_year']/df_booking['arrival_date_year'].sum() * 100, 1)

df_booking['arrival_date_year'].value_counts(dropna=True).plot(kind="bar")
xlocs, xlabs = plt.xticks()

for i, v in enumerate(df_booking['percentage']):

    plt.text(xlocs[i] - 0.08, v + 25, str(v) + '%', fontsize = 15)

plt.title('Booking')
plt.show()

给出的错误信息是

IndexError                                Traceback (most recent call last)

<ipython-input-59-07b4659a45f8> in <module>()
     21 for i, v in enumerate(df_booking['percentage']):
     22 
---> 23     plt.text(xlocs[i] - 0.08, v + 25, str(v) + '%', fontsize = 15)
     24 
     25 plt.title('Booking')

IndexError: index 3 is out of bounds for axis 0 with size 3

【问题讨论】:

  • 请编辑您的帖子并粘贴您的整个代码
  • 列中的所有百分比均为 0。此外,您尝试使用列中的 119390 个值注释 3 个条形。
  • @TrentonMcKinney 输出显示为零,但这不应该是实际值...它应该是 100 分为三个值

标签: python pandas dataframe matplotlib seaborn


【解决方案1】:

处理您当前的代码,存储计数,然后计算百分比,然后使用百分比添加刻度:

counts = df['arrival_date_year'].value_counts(dropna=True)
perc = round(100*counts/counts.sum(),1).to_numpy()

counts.plot(kind="bar")

xlocs, xlabs = plt.xticks()

for i in range(len(da)):

    plt.text(xlocs[i] - 0.08, counts.iloc[i] + 25, str(perc[i]) + '%', fontsize = 10)

plt.title('Booking')
plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-06-12
    • 2019-06-08
    • 1970-01-01
    • 2019-09-27
    • 2021-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-12-04
    相关资源
    最近更新 更多