import csv import matplotlib.pylab as plt import numpy as np #导入csv文件 file = 'D:\\education.csv' with open(file, encoding='utf_8', newline='') as f: data = [row for row in csv.DictReader(f)] print(data) f.close() #可视化操作 plt.rcParams["font.family"]="FangSong" #设置字体 #设置横坐标 x_trick=[] for dct in data: x_trick.append(dct.get("地区")) #设置纵坐标 #小学 y_num1=[] for n1 in data: y_num1.append(n1.get('小学')) y1 = [int(x) for x in y_num1] #初中 y_num2 = [] for n2 in data: y_num2.append(n2.get('初中')) y2 = [int(x) for x in y_num2] #高中 y_num3 = [] for n3 in data: y_num3.append(n3.get('初中')) y3 = [int(x) for x in y_num3] #大学 y_num4 = [] for n4 in data: y_num4.append(n4.get('初中')) y4 = [int(x) for x in y_num4] #无学历 count = [i+j+m+n for i,j,m,n in zip(y1, y2, y3, y4)] y0 = [100000 - i for i in count] plt.figure(figsize=(10,5)) #设置表格大小 plt.title('各地区每10完人不同教育程度的人数', loc='left', fontsize=10) x=range(0,len(x_trick)) #刻度 plt.xticks(x,x_trick) #横坐标对应位置显示的内容 #在特定的起始高度画出每条对应的柱子,并给定相应的颜色 plt.bar(x,y0,color='rad') plt.bar(x,y1, color='orange', bottom=np.array(y0)) plt.bar(x, y2, color='yellow', bottom=np.array(y0)+np.array(y1)) plt.bar(x, y3, color='green', bottom=np.array(y0)+np.array(y1)+np.array(y2)) plt.bar(x, y4, color='blue', bottom=np.array(y0)+np.array(y1)+np.array(y2)+np.array(y3)) #创建图例 plt.legend(['五', '小学', '初中', '高中(含中专)', '大学(大专及以上)'], ncol=5,bbox_to_anchor=(1.001,1.054), borderaxespad=0, fontsize=6, loc=1, ) plt.show() 请修改这段代码
时间: 2024-04-28 19:22:04 浏览: 127
解决python中显示图片的plt.imshow plt.show()内存泄漏问题
import csv
import matplotlib.pylab as plt
import numpy as np
#导入csv文件
file = 'D:\\education.csv'
with open(file, encoding='utf_8', newline='') as f:
data = [row for row in csv.DictReader(f)]
print(data)
f.close()
#可视化操作
plt.rcParams["font.family"]="FangSong" #设置字体
#设置横坐标
x_trick=[]
for dct in data:
x_trick.append(dct.get("地区"))
#设置纵坐标
#小学
y_num1=[]
for n1 in data:
y_num1.append(n1.get('小学'))
y1 = [int(x) for x in y_num1]
#初中
y_num2 = []
for n2 in data:
y_num2.append(n2.get('初中'))
y2 = [int(x) for x in y_num2]
#高中
y_num3 = []
for n3 in data:
y_num3.append(n3.get('高中'))
y3 = [int(x) for x in y_num3]
#大学
y_num4 = []
for n4 in data:
y_num4.append(n4.get('大学'))
y4 = [int(x) for x in y_num4]
#无学历
count = [i+j+m+n for i,j,m,n in zip(y1, y2, y3, y4)]
y0 = [100000 - i for i in count]
plt.figure(figsize=(10,5)) #设置表格大小
plt.title('各地区每10万人不同教育程度的人数', loc='left', fontsize=10)
x=range(0,len(x_trick)) #刻度
plt.xticks(x,x_trick) #横坐标对应位置显示的内容
#在特定的起始高度画出每条对应的柱子,并给定相应的颜色
plt.bar(x,y0,color='red')
plt.bar(x,y1, color='orange', bottom=np.array(y0))
plt.bar(x, y2, color='yellow', bottom=np.array(y0)+np.array(y1))
plt.bar(x, y3, color='green', bottom=np.array(y0)+np.array(y1)+np.array(y2))
plt.bar(x, y4, color='blue', bottom=np.array(y0)+np.array(y1)+np.array(y2)+np.array(y3))
#创建图例
plt.legend(['无学历', '小学', '初中', '高中(含中专)', '大学(大专及以上)'],
ncol=5,bbox_to_anchor=(1.001,1.054),
borderaxespad=0,
fontsize=6,
loc=1,
)
plt.show()
阅读全文