如何将 csv 数据转换为条形图?

How do I convert csv data into bar chart?

我已经使用 csv 数据绘制了线图并将 matplotlib.pyplot 导入为 plt charge、total 和 year 已经按行追加。

我的代码

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()

这是当前线图的样子:

我该如何编码才能使它变成这样的条形图:

有一个example in the matplotlib site and you can find another approach of your issue 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()