【问题标题】:How do I convert csv data into bar chart? [duplicate]如何将 csv 数据转换为条形图? [复制]
【发布时间】:2021-09-22 05:35:48
【问题描述】:

我已经使用 csv 数据绘制了线图并将 matplotlib.pyplot 作为 plt 导入 费用、总计和年份已按行追加。

我的代码

plt.plot(year, charge, '-g', label = 'Chargeable Income')
plt.plot(year, total, '-r', label = 'Total Income')
plt.title('Chargeable and Total Income VS Year')
plt.xlabel('Year')
plt.ylabel('(S$)')

plt.grid()
plt.legend()
plt.show()

这是当前线图的样子:

我如何编码使其变成这样的条形图:

【问题讨论】:

    标签: python csv bar-chart


    【解决方案1】:

    matplotlib 站点中有一个example,您可以找到解决问题的另一种方法here。基本上,您只需按宽度移动 x 值。这是相关的位:

    import numpy as np
    import matplotlib.pyplot as plt
    # create sample data as np.array in the provided format year | chargeable | total
    arr = np.array([[2017, 375873, 78833], [2018, 783893, 98288]])
    
    ind = np.arange(arr.shape[0])  # the x locations for the groups
    width = 0.35       # the width of the bars
    
    fig = plt.figure()
    ax = fig.add_subplot(111)
    rects1 = ax.bar(ind, arr[:, 2], width, color='royalblue')
    
    rects2 = ax.bar(ind+width, arr[:, 1], width, color='seagreen')
    
    # add some
    ax.set_ylabel('(S$)')
    ax.set_ylabel('Year')
    ax.set_title('Chargeable and Total Income VS Year')
    ax.set_xticks(ind + width / 2)
    ax.set_xticklabels( arr[:, 0] )
    
    ax.legend( (rects1[0], rects2[0]), ('Chargeable Income', 'Total Income') )
    
    plt.show()
    

    【讨论】:

    • 而不是输入 "arr = np.array([[2017, 375873, 78833], [2018, 783893, 98288]])" 有没有其他方法可以从 csv 数据中获取数字因为我已经导入了 csv 并且还附加了年份、费用和总收入?
    • 你指的是哪个数字?您的意思是如何访问例如导入的 csv 数据中的特定行或加载值而不导入 csv 文件?您能否更准确地定义您的问题?
    • 我会尽量解释清楚。因此,假设我想将“应收费”和“总收入”与“年”显示为条形图,这意味着我需要告诉代码它们每个的值是什么。除了手动输入“2017、375873、78833”等年份,还有其他方法可以直接检索数据并显示吗?我不希望输入每年的每个值。我已经在我的代码中将 Year、Total_Income 和 Chargeable_Income 的所有值指定为 year、total 和 charge。
    • @Jon 如果您的数据采用.csv.xlsx 文件格式(或其他表格格式),您可以轻松地将它们作为数组导入python。
    • 哦,是的,我该怎么做
    猜你喜欢
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 2021-03-30
    • 2021-07-19
    • 2021-08-18
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    相关资源
    最近更新 更多