用CSV d创建条形图

2024-04-29 08:23:50 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我要用CSV文件中的数据创建堆积条形图,生成类似于 graph

这是数据

Date,Kitchen,Laundry,Aircon&heater,Others
Jan/2010,53.887,56.568,395.913,483.293
Feb/2010,49.268,53.590,411.714,409.956
Mar/2010,35.089,60.872,324.352,382.285
Apr/2010,38.196,36.476,336.091,328.872
May/2010,48.107,52.376,364.625,349.765
Jun/2010,65.747,47.675,306.934,277.734
Jul/2010,17.667,34.359,192.912,291.525
Aug/2010,12.499,26.983,160.189,168.719
Sep/2010,36.865,32.508,257.861,277.923
Oct/2010,48.199,60.220,315.669,441.461
Nov/2010,45.082,41.897,237.124,394.402

我知道如何创建图表/堆叠它和材料,问题是我不知道如何导入和使用文件中的数据来绘制它。帮助?


Tags: 文件csv数据dateheateraprmarmay
1条回答
网友
1楼 · 发布于 2024-04-29 08:23:50

嘿,你也可以使用numpy.loadtxt来读取你的数据。我试过了,希望这是你想要的:

import matplotlib.pyplot as plt
import numpy as np

# import data with loadtxt, but only the relevant floats. 
# data.csv is the file as you have given it above
data = np.loadtxt('data.csv', delimiter=',', skiprows = 1, usecols = range(1,5))
data = data.transpose()

# import the tick labels
xt = np.loadtxt('data.csv', dtype='str', delimiter=',', skiprows = 1, usecols = (0,))

剩下的就是像你一样绘制条形图:

width = 0.45
ind = np.arange(11) + 0.75

fig, ax = plt.subplots(1,1)
p0 = ax.bar(ind, data[0],  width, color = 'cyan')
p1 = ax.bar(ind, data[1], width, bottom = data[0], color = 'violet')
p2 = ax.bar(ind, data[2], width, bottom = data[0] + data[1], color = 'g')
p3 = ax.bar(ind, data[3], width, bottom = data[0] + data[1] + data[2], color = 'r')

ax.set_ylabel('kWh')
ax.set_xlabel('month')
ax.set_xticks (ind + width/2.)
ax.set_xticklabels( xt, rotation = 70 )

fig.legend( (p0[0], p1[0], p2[0], p3[0]), ('kitchen', 'laundry', 'aircon&heater', 'other') )
fig.tight_layout()
fig.show()

这给了我以下的情节: enter image description here

相关问题 更多 >