from pyecharts.charts import Bar, Timeline from pyecharts.options import * from pyecharts.globals import ThemeType import xlrd from pyecharts.charts import Bar from pyecharts.options import ItemStyleOpts, LabelOpts wb = xlrd.open_workbook('/Users/kelima/Downloads/python/柱状图.xls') print(wb) sheetname = wb.sheet_names()[0] # 通过指定的表单名称获取Sheet对象(工作表) sheet = wb.sheet_by_name(sheetname) # 通过Sheet对象的nrows和ncols属性获取表单的行数和列数 print(sheet.nrows, sheet.ncols) scores_dict = {} # 创建空字典,用于存储各年的数据 labelsrow = sheet.row_slice(0, 1, 9) # 获取 Excel 表头的标签,即年信息所在的行(第一行) print(labelsrow,'labelsrow') for row in range(sheet.nrows): # 遍历 Excel 表格的每一行 if row > 0: # 跳过第一行,因为第一行是表头 valuerow = int(sheet.cell(row, 0).value) # 获取年信息所在的列(第一列)的数值 scores_dict[valuerow] = [] # 以该年数值为键,创建一个空列表为值,存储该年级下的每个项目分数 for col in range(sheet.ncols): # 遍历年下的每个项目的分数,从第二列开始遍历 if col > 0: arr1 = [labelsrow[col-1].value , sheet.cell(row, col).value] # 将科目和分数添加到列表中 scores_dict[valuerow].append(arr1) data_lines=scores_dict print(data_lines) # 先定义一个字典 data_dict = {} for line in data_lines: item = data_lines[line] year = int(line) # 年份 country = [] #项目名称 GDP = [] #各项的值 for item1 in item: # itemvalue = item[item1] country.append(item1[0]) # 项目名称匹配值 if not item1[1]: #对空值赋值0 item1[1] = 0 GDP.append(round(float(item1[1])/10000,2)) # 取值取小数点后两位 # 如何判断字典里面有没有制定的key呢? try: data_dict[year].append([country, GDP]) except KeyError: data_dict[year] = [] data_dict[year].append([country, GDP]) # 排序年份 sorted_year_list = sorted(data_dict.keys()) timeline = Timeline({"theme": ThemeType.LIGHT}) # 创建时间线对象 for year in sorted_year_list: data_dict[year].sort(key=lambda element: element[1], reverse=True) # 取出本年份前八名的国家 year_data = data_dict[year] x_data = [] y_data = [] for country_gdp in year_data: x_data = country_gdp[0] [4:7] # x轴项目名称 y_data = country_gdp[1] [4:7] # y轴添加各项目的数据,单位为亿元 print(x_data,'x_data') print(y_data,'country_gdp[1]') # 构建柱状图 bar = Bar() # x_data.reverse() # y_data.reverse() bar.add_xaxis(x_data) bar.add_yaxis("亿元", y_data, label_opts=LabelOpts(position="right"),itemstyle_opts=ItemStyleOpts(color='#D2B48C'), bar_width=60,) # 反转x轴,y轴 bar.reversal_axis() # 设置每一年的图表标题 bar.set_global_opts( title_opts=TitleOpts(title=f"{year}年", pos_right=100, pos_bottom=200, title_textstyle_opts=TextStyleOpts(color='#CD5C5C', font_size=50) ), visualmap_opts=VisualMapOpts(min_=0, max_=10, range_color=['#D2B48C','#DC143C','#87CEFA','#90EE90' ], is_show=False, ), xaxis_opts=AxisOpts( axislabel_opts=LabelOpts(font_size=18), # 设置 x 轴标签字体大小为 16 is_show=True, # x轴不显示网格线 is_scale=False, # 是否开启坐标轴刻度自适应,默认为 False interval=20, # 坐标轴刻度间隔,默认为 None ), yaxis_opts=AxisOpts(axislabel_opts=LabelOpts(font_size=16),max_=1, min_=0), # 通过这个命令实现了数据格固定,柱状持续增长 ) # 创建时间线对象 timeline.add(bar, str(year)) # 设置时间为自动播放 timeline.add_schema( play_interval=1000, # 时间间隔 is_timeline_show=True, # 是否显示时间 is_loop_play=True, # 是否循环 is_auto_play=True # 是否自动播放 ) # 绘图 file_name = 'bar.html' timeline.render(file_name)
python 关于生成动态柱状图
最新推荐文章于 2024-02-05 20:32:06 发布