import matplotlib.pyplot as plt
import matplotlib
import matplotlib.figure
import matplotlib.transforms as mtransforms
from matplotlib.ticker import FuncFormatter
from adjustText import adjust_text
from matplotlib import cm
import json,os
import matplotlib.ticker as ticker
import matplotlib.cbook as cbook
from matplotlib import font_manager
from cycler import cycler
import numpy as np
from pyecharts.charts import Map,Bar,Grid,PictorialBar
from pyecharts import options as opts
from pyecharts.render import make_snapshot
from snapshot_selenium import snapshot

# RGB格式颜色转换为16进制颜色格式
def RGB_list_to_Hex(RGB):
	color = '#'
	for i in RGB:
		num = int(i)
		color += str(hex(num))[-2:].replace('x', '0').upper()
	return color


# 16进制颜色格式颜色转换为RGB格式
def Hex_to_RGB(hex):
	r = int(hex[1:3], 16)
	g = int(hex[3:5], 16)
	b = int(hex[5:7], 16)
	rgb = str(r) + ',' + str(g) + ',' + str(b)
	return rgb, [r, g, b]


# 生成渐变色
def gradient_color(color_list, color_sum=3):
	color_center_count = len(color_list)
	color_sub_count = int(color_sum / (color_center_count - 1))
	color_index_start = 0
	color_map = []
	for color_index_end in range(1, color_center_count):
		color_rgb_start = Hex_to_RGB(color_list[color_index_start])[1]
		color_rgb_end = Hex_to_RGB(color_list[color_index_end])[1]
		r_step = (color_rgb_end[0] - color_rgb_start[0]) / color_sub_count
		g_step = (color_rgb_end[1] - color_rgb_start[1]) / color_sub_count
		b_step = (color_rgb_end[2] - color_rgb_start[2]) / color_sub_count
		# 生成中间渐变色
		now_color = color_rgb_start
		color_map.append(RGB_list_to_Hex(now_color))
		for color_index in range(1, color_sub_count):
			now_color = [now_color[0] + r_step, now_color[1] + g_step, now_color[2] + b_step]
			color_map.append(RGB_list_to_Hex(now_color))
		color_index_start = color_index_end
	return color_map


def fixed_color(color_list, color_sum=3):
	color_center_count = len(color_list)
	color_sub_count = int(color_sum / (color_center_count - 1))
	color_map = []
	for color_index_end in range(1, color_center_count):
		for color_index in range(1, color_sub_count):
			color_map.append(color_list[0])
	return color_map


# 文字标签换行，每行n个字
def add_newline(str,num):
	n = len(str) // num
	newstr = ''
	if len(str) % num == 0:
		for i in range(n):
			newstr = newstr + str[i * num:(i + 1) * num] + '\n'
	else:
		for i in range(n + 1):
			newstr = newstr + str[i * num:(i + 1) * num] + '\n'
	newstr = newstr[:-1]
	return newstr


# 去除导出图片的周围留白
def del_blank():
	plt.gca().xaxis.set_major_locator(plt.NullLocator())
	plt.gca().yaxis.set_major_locator(plt.NullLocator())
	plt.subplots_adjust(top=1,bottom=0,left=0,right=1,hspace=0,wspace=0)
	plt.margins(0,0)


#柱状图
def bar(datasource):
	plt.close("all")
	global colors
	matplotlib.rcParams['font.size'] = datasource['figure']['fontsize']
	seriescolor=["#3E8EB9", "#F08300", "#838B98", "#81CDE4", "#B1C7D2", "#91A64D", "#023A4A",
				 "#904F00", "#2690B0", "#405E6E"]
	gradientcolor=gradient_color(["#3E8EB9", "#3E8EB9"], color_sum=len(datasource['Yaxis'][0]['data']))
	if datasource['style']['prop_cycle']['series']:
		colors=seriescolor
	if datasource['style']['prop_cycle']['gradient']:
		colors=gradientcolor
	fig = plt.figure(figsize=(datasource['figure']['figsize']))
	ax=fig.add_subplot()
	label=datasource['Xaxis'][0]['axisLabel']['label']
	if datasource['Xaxis'][0]['wordnum']:
		label=[add_newline(i,datasource['Xaxis'][0]['wordnum']) for i in label]
	x=np.arange(len(label))
	seriesnum=len(datasource['Yaxis'])
	#bar_width=0.6/seriesnum
	bar_width,texts,labels = 0.4,[],[]
	for i in range(seriesnum):
		if seriesnum == 1:
			ax.bar(x + i * bar_width, datasource['Yaxis'][i]['data'], width=bar_width,
				   label=datasource['Yaxis'][i]['seriesname'], color=colors)  # 固定一种颜色
		else:
			ax.bar(x + i * bar_width, datasource['Yaxis'][i]['data'], width=bar_width,
				   label=datasource['Yaxis'][i]['seriesname'], color=colors[i])
		labels.append(datasource['Yaxis'][i]['seriesname'])
		if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
			for a, b in zip(x + i * bar_width, datasource['Yaxis'][i]['data']):
				texts.append(ax.text(float(a), float(b),
									 format(float(b), datasource['textstyle']['format']) + "%",
									 ha=datasource['textstyle']['horizontalalignment'],
									 va=datasource['textstyle']['verticalalignment']))
			def to_percent(y,pos):
				return "{0}{1}".format(datasource['Yaxis'][i]['axisLabel']['format'][1] % y, "%")
			formatter=ticker.FuncFormatter(to_percent)
		else:
			for a, b in zip(x + i * bar_width, datasource['Yaxis'][i]['data']):
				texts.append(ax.text(float(a), float(b), format(float(b), datasource['textstyle']['format']),
									 ha=datasource['textstyle']['horizontalalignment'],
									 va=datasource['textstyle']['verticalalignment']))
			formatter=ticker.FormatStrFormatter(datasource['Yaxis'][i]['axisLabel']['format'])
		ax.yaxis.set_major_formatter(formatter)
	if datasource['autoadjust']['adjustText']:
		adjust_text(texts,
					autoalign=datasource['autoadjust']['autoalign'],
					only_move={"points": datasource['autoadjust']['only_move']['points'],
							   "text": datasource['autoadjust']['only_move']['text'],
							   "objects": datasource['autoadjust']['only_move']['objects']})
	ax.set_xticks(x+bar_width*((seriesnum-1)/2))
	ax.set_xticklabels(label)
	ax.set_xlim(-1,len(label))
	if datasource['legend']['show']:
		ax.legend(loc=datasource['legend']['location'],
			ncol=eval(datasource['legend']['ncol']),
			bbox_to_anchor=tuple(datasource['legend']['bbox_to_anchor']),
			frameon=datasource['legend']['frameon'],labels=labels)
	if datasource['autoadjust']['tight_layout']:
		fig.tight_layout()
	if datasource['autoadjust']['autofmt_xdate']:
		fig.autofmt_xdate()
	ax.tick_params(bottom=datasource['ticks']['bottom'],
				   top=datasource['ticks']['top'],
				   left=datasource['ticks']['left'],
				   right=datasource['ticks']['right'])  # 移除全部刻度线
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


#堆积柱状图+数据表
def stackbar(datasource):
	plt.close("all")
	matplotlib.rcParams['font.size'] = datasource['figure']['fontsize']
	seriescolor = ["#3E8EB9", "#F08300", "#838B98", "#81CDE4", "#B1C7D2", "#91A64D", "#E2D700", "#023A4A", "#904F00", "#2690B0",
				   "#405E6E"]
	fig = plt.figure(figsize=(datasource['figure']['figsize']))
	ax = fig.add_subplot()
	label = datasource['Xaxis'][0]['axisLabel']['label']
	if datasource['Xaxis'][0]['wordnum']:
		label = [add_newline(i, datasource['Xaxis'][0]['wordnum']) for i in label]
	seriesnum = len(datasource['Yaxis'])
	y_offset = np.zeros(len(label))
	seriescolor = seriescolor[:seriesnum]
	texts, seriesnames, colors = [], [], []
	for i in range(seriesnum):
		ydata = datasource['Yaxis'][i]['data']
		seriesname = datasource['Yaxis'][i]['seriesname']
		color = seriescolor[::-1][i]
		ax.bar(label, ydata, bottom=y_offset, color=color,
			   width=datasource['bars']['bar_width'], label=seriesname)
		y_offset = y_offset + ydata
		if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
			texts.append([format(i, datasource['textstyle']['format']) + "%" for i in ydata])
		else:
			texts.append([format(i, datasource['textstyle']['format']) for i in ydata])
		seriesnames.append(seriesname)
		colors.append(color)
		if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
			def to_percent(y, pos):
				return datasource['Yaxis'][i]['axisLabel']['format'][1] % (y) + "%"
			formatter = ticker.FuncFormatter(to_percent)
		else:
			formatter = ticker.FormatStrFormatter(datasource['Yaxis'][i]['axisLabel']['format'])
		ax.yaxis.set_major_formatter(formatter)
	plt.xticks(())
	ax.tick_params(bottom=datasource['ticks']['bottom'],
				   top=datasource['ticks']['top'],
				   left=datasource['ticks']['left'],
				   right=datasource['ticks']['right'])  # 移除全部刻度线
	# 添加数据表
	texts.reverse()
	colors = colors[::-1]
	seriesnames = seriesnames[::-1]
	ax.table(cellText=texts,rowLabels=seriesnames,colLabels=label,loc='bottom',cellLoc='center',
			 rowLoc='center',fontsize=20,bbox=[0, -0.5, 1, 0.5])
	plt.subplots_adjust(left=0.2, bottom=0.3, right=0.9, top=0.9)
	if datasource['autoadjust']['adjustText']:
		adjust_text(texts,
					autoalign=datasource['autoadjust']['autoalign'],
					only_move={"points": datasource['autoadjust']['only_move']['points'],
							   "text": datasource['autoadjust']['only_move']['text'],
							   "objects": datasource['autoadjust']['only_move']['objects']}
					)
	if datasource['legend']['show']:
		ax.legend(loc=datasource['legend']['location'],
				  ncol=eval(datasource['legend']['ncol']),
				  bbox_to_anchor=tuple(datasource['legend']['bbox_to_anchor']),
				  frameon=datasource['legend']['frameon'])
	if datasource['autoadjust']['tight_layout']:
		fig.tight_layout()
	if datasource['autoadjust']['autofmt_xdate']:
		fig.autofmt_xdate()
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


# 堆积条形图
def stackbarh(datasource):
	plt.close("all")
	seriescolor=["#04617B", "#F08300", "#81CDE4", "#739AAE", "#819933", "#E2D700", "#023A4A", "#904F00", "#2690B0", "#405E6E"]
	fig=plt.figure(figsize=(datasource['figure']['figsize']))
	ax=fig.add_subplot()
	label=datasource['Xaxis'][0]['axisLabel']['label']
	x=np.arange(len(label))
	if datasource['Xaxis'][0]['wordnum']:
		label=[add_newline(i,datasource['Xaxis'][0]['wordnum']) for i in label]
	seriesnum=len(datasource['Yaxis'])
	y_offset=np.zeros(len(label))
	seriescolor=seriescolor[:seriesnum]
	texts=[]
	for i in range(seriesnum):
		ydata=datasource['Yaxis'][i]['data']
		seriesname=datasource['Yaxis'][i]['seriesname']
		color=seriescolor[::-1][i]
		ax.barh(label,ydata,left=y_offset,color=color,
			height=datasource['bars']['bar_width'],label=seriesname)
		y_offset=y_offset+ydata

		if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
			for a, b, c in zip(ydata, x, y_offset):
				texts.append(ax.text(c - a / 2, b, format(float(a), datasource['textstyle']['format']) + "%",
									 va=datasource['textstyle']['horizontalalignment'],
									 ha=datasource['textstyle']['verticalalignment']))
			def to_percent(y,pos):
				return "{0}{1}".format(datasource['Yaxis'][i]['axisLabel']['format'][1]%(y/100),"%")
			formatter=ticker.FuncFormatter(to_percent)
		else:
			for a, b, c in zip(ydata, x, y_offset):
				texts.append(ax.text(c - a / 2, b, format(float(a), datasource['textstyle']['format']),
									 va=datasource['textstyle']['horizontalalignment'],
									 ha=datasource['textstyle']['verticalalignment']))
			formatter=ticker.FormatStrFormatter(datasource['Yaxis'][i]['axisLabel']['format'])
		ax.yaxis.set_major_formatter(formatter)
	ax.set_yticklabels(label)
	if datasource['spines']['bottom']==0:
		ax.spines['bottom'].set_visible(0)
		ax.set_xticks(())
	if datasource['autoadjust']['adjustText']:
		adjust_text(texts)
	if datasource['legend']['show']:
		ax.legend(loc=datasource['legend']['location'],
			ncol=eval(datasource['legend']['ncol']),
			bbox_to_anchor=tuple(datasource['legend']['bbox_to_anchor']),
			frameon=datasource['legend']['frameon'])
	if datasource['autoadjust']['tight_layout']:
		fig.tight_layout()
	if datasource['autoadjust']['autofmt_xdate']:
		fig.autofmt_xdate()
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


#条形图
def barh(datasource):
	plt.close("all")
	seriescolor=["#3E8EB9", "#F08300", "#838B98", "#81CDE4", "#B1C7D2", "#91A64D", "#023A4A", "#904F00", "#2690B0", "#405E6E"]
	gradientcolor=fixed_color(["#3E8EB9", "#3E8EB9"], color_sum=len(datasource['Yaxis'][0]['data']))
	fig=plt.figure(figsize=(datasource['figure']['figsize']))
	ax=fig.add_subplot()
	label=datasource['Xaxis'][0]['axisLabel']['label'][::-1]
	x=np.arange(len(label))
	seriesnum=len(datasource['Yaxis'])
	#bar_width=0.6/seriesnum
	bar_width = 0.4
	texts=[]
	for i in range(seriesnum-1,-1,-1):
		y=datasource['Yaxis'][i]['data'][::-1]
		if seriesnum==1:
			#ax.barh(x-i*bar_width,y,height=bar_width,color=gradientcolor)
			ax.barh(x - i * bar_width, y, height=bar_width, color=seriescolor[0])
		else:
			ax.barh(x-i*bar_width,y,height=bar_width,color=seriescolor[i],label=datasource['Yaxis'][i]['seriesname'])

		if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
			for a, b in zip(y, x - i * bar_width):
				texts.append(ax.text(float(a), float(b), format(float(a), datasource['textstyle']['format']) + "%",
									 va=datasource['textstyle']['horizontalalignment'],
									 ha=datasource['textstyle']['verticalalignment']))
			def to_percent(y,pos):
				return "{0}{1}".format(datasource['Yaxis'][i]['axisLabel']['format'][1] % y, "%")
			formatter=ticker.FuncFormatter(to_percent)
		else:
			for a, b in zip(y, x - i * bar_width):
				texts.append(ax.text(float(a), float(b), format(float(a), datasource['textstyle']['format']),
									 va=datasource['textstyle']['horizontalalignment'],
									 ha=datasource['textstyle']['verticalalignment']))
			formatter=ticker.FormatStrFormatter(datasource['Yaxis'][i]['axisLabel']['format'])
		ax.yaxis.set_major_formatter(formatter)
	if datasource['autoadjust']['adjustText']:
		adjust_text(texts,
					autoalign=datasource['autoadjust']['autoalign'],
					only_move={"points": datasource['autoadjust']['only_move']['points'],
							   "text": datasource['autoadjust']['only_move']['text'],
							   "objects": datasource['autoadjust']['only_move']['objects']}
					)
	ax.set_yticks(x-bar_width*((seriesnum-1)/2))
	ax.set_yticklabels(label)
	ax.set_ylim(-1, len(label))
	if datasource['spines']['bottom']==0:
		ax.spines['bottom'].set_visible(0)
		ax.set_xticks(())
	if datasource['legend']['show']:
		ax.legend(loc=datasource['legend']['location'],
			ncol=eval(datasource['legend']['ncol']),
			bbox_to_anchor=tuple(datasource['legend']['bbox_to_anchor']),
			frameon=datasource['legend']['frameon'])
	if datasource['autoadjust']['tight_layout']:
		fig.tight_layout()
	if datasource['autoadjust']['autofmt_xdate']:
		fig.autofmt_xdate()
	ax.tick_params(bottom=datasource['ticks']['bottom'],
				   top=datasource['ticks']['top'],
				   left=datasource['ticks']['left'],
				   right=datasource['ticks']['right'])  # 移除全部刻度线
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


#左右条形图
def rl_barh(datasource):
	plt.close("all")
	seriescolor=["#04617B", "#F08300", "#81CDE4", "#739AAE", "#819933", "#E2D700", "#023A4A", "#904F00", "#2690B0", "#405E6E"]
	fig=plt.figure()
	ax=fig.add_subplot()
	label=datasource['Xaxis'][0]['axisLabel']['label']
	x=np.arange(len(label))
	y1=[-i for i in datasource['Yaxis'][0]['data']]
	y2=datasource['Yaxis'][1]['data']
	seriesnum=len(datasource['Yaxis'])
	bar_width=0.6/seriesnum
	ax.barh(x,y1,height=bar_width,label=datasource['Yaxis'][0]['seriesname'],color=seriescolor[0])
	ax.barh(x,y2,height=bar_width,label=datasource['Yaxis'][1]['seriesname'],color=seriescolor[1])
	for a,b in zip(y1,x):
		ax.text(a+0.2,b,format(-a,datasource['Yaxis'][0]['axisLabel']['format']),
				va=datasource['textstyle']['horizontalalignment'],
				ha=datasource['textstyle']['verticalalignment'])
	for a,b in zip(y2,x):
		ax.text(a-0.2,b,format(a,datasource['Yaxis'][1]['axisLabel']['format']),
				va=datasource['textstyle']['horizontalalignment'],
				ha=datasource['textstyle']['verticalalignment'])
	ax.set_yticks(x+bar_width*((seriesnum-1)/2))
	ax.set_yticklabels(label)
	if datasource['spines']['bottom']==0:
		ax.spines['bottom'].set_visible(0)
		ax.set_xticks(())
	if datasource['legend']['show']:
		ax.legend(loc=datasource['legend']['location'],
			ncol=eval(datasource['legend']['ncol']),
			bbox_to_anchor=tuple(datasource['legend']['bbox_to_anchor']),
			frameon=datasource['legend']['frameon'])
	if datasource['autoadjust']['tight_layout']:
		fig.tight_layout()
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


# 折线图
def plot(datasource):
	plt.close("all")
	seriescolor=["#04617B", "#F08300", "#81CDE4", "#739AAE", "#819933", "#E2D700", "#023A4A", "#904F00", "#2690B0", "#405E6E"]
	fig=plt.figure()
	ax=fig.add_subplot()
	label=datasource['Xaxis'][0]['axisLabel']['label']
	if datasource['Xaxis'][0]['wordnum']:
		label=[add_newline(i,datasource['Xaxis'][0]['wordnum']) for i in label]
	seriesnum=len(datasource['Yaxis'])
	texts,seriesnames,colors=[],[],[]
	for i in range(seriesnum):
		seriesname=datasource['Yaxis'][i]['seriesname']
		color=seriescolor[i]
		ydata=datasource['Yaxis'][i]['data']
		ax.plot(label,ydata,label=datasource['Yaxis'][i]['seriesname'],color=color)
		texts.append([format(i,datasource['textstyle']['format']) for i in ydata])
		seriesnames.append(seriesname)
		colors.append(color)
		if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
			for a, b in zip(label, datasource['Yaxis'][i]['data']):
				texts.append(ax.text(a, b, format(float(b), datasource['textstyle']['format']) + "%",
									 va=datasource['textstyle']['horizontalalignment'],
									 ha=datasource['textstyle']['verticalalignment']))
			def to_percent(y,pos):
				return "{0}{1}".format(datasource['Yaxis'][i]['axisLabel']['format'][1]%(y),"%")
			formatter=ticker.FuncFormatter(to_percent)
		else:
			for a, b in zip(label, datasource['Yaxis'][i]['data']):
				texts.append(ax.text(a, b, format(float(b), datasource['textstyle']['format']),
									 va=datasource['textstyle']['horizontalalignment'],
									 ha=datasource['textstyle']['verticalalignment']))
			formatter=ticker.FormatStrFormatter(datasource['Yaxis'][i]['axisLabel']['format'])
		ax.yaxis.set_major_formatter(formatter)
		try:
			ax.set_ylim(datasource['Yaxis'][i]['limit'])
		except:
			pass
	if datasource['autoadjust']['adjustText']:
			adjust_text(texts)
	#ax.set_xticklabels(label, dict(size = 10.5))
	ax.set_xticklabels(label)
	if datasource['legend']['show']:
		ax.legend(loc=datasource['legend']['location'],
			ncol=eval(datasource['legend']['ncol']),
			bbox_to_anchor=tuple(datasource['legend']['bbox_to_anchor']),
			frameon=datasource['legend']['frameon'])
	if datasource['autoadjust']['tight_layout']:
		fig.tight_layout()
	if datasource['autoadjust']['autofmt_xdate']:
		fig.autofmt_xdate()
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


# 多系列线型图+数据表
def plots(datasource):
	plt.close("all")
	seriescolor=["#04617B", "#F08300", "#81CDE4", "#739AAE", "#819933", "#E2D700", "#023A4A", "#904F00", "#2690B0", "#405E6E"]
	fig=plt.figure()
	ax=fig.add_subplot()
	label=datasource['Xaxis'][0]['axisLabel']['label']
	if datasource['Xaxis'][0]['wordnum']:
		label=[add_newline(i,datasource['Xaxis'][0]['wordnum']) for i in label]
	seriesnum=len(datasource['Yaxis'])
	texts,seriesnames,colors=[],[],[]
	for i in range(seriesnum):
		seriesname=datasource['Yaxis'][i]['seriesname']
		color=seriescolor[i]
		ydata=datasource['Yaxis'][i]['data']
		ax.plot(label,ydata,label=datasource['Yaxis'][i]['seriesname'],color=color)
		if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
			texts.append([format(i, datasource['textstyle']['format']) + "%" for i in ydata])
		else:
			texts.append([format(i, datasource['textstyle']['format']) for i in ydata])
		seriesnames.append(seriesname)
		colors.append(color)
		if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
			def to_percent(y,pos):
				return "{0}{1}".format(datasource['Yaxis'][i]['axisLabel']['format'][1]%(y),"%")
			formatter=ticker.FuncFormatter(to_percent)
		else:
			formatter=ticker.FormatStrFormatter(datasource['Yaxis'][i]['axisLabel']['format'])
		ax.yaxis.set_major_formatter(formatter)
		try:
			ax.set_ylim(datasource['Yaxis'][i]['limit'])
		except:
			pass
	plt.xticks(())
	# 添加数据表
	texts.reverse()
	colors=colors[::-1]
	seriesnames=seriesnames[::-1]
	datatable=ax.table(cellText=texts,
		rowLabels=seriesnames,
		colLabels=label,
		loc='bottom',
		cellLoc='center',
		rowLoc='center',
		# rowColours=colors,
		fontsize=15,
		bbox = [0,-0.7,1,0.7]
		)
	plt.subplots_adjust(left=0.2, bottom=0.4,right=0.9,top=0.9)
	if datasource['autoadjust']['adjustText']:
			adjust_text(texts)
	ax.set_xticklabels(label)
	if datasource['legend']['show']:
		ax.legend(loc=datasource['legend']['location'],
			ncol=eval(datasource['legend']['ncol']),
			bbox_to_anchor=tuple(datasource['legend']['bbox_to_anchor']),
			frameon=datasource['legend']['frameon'])
	if datasource['autoadjust']['tight_layout']:
		fig.tight_layout()
	if datasource['autoadjust']['autofmt_xdate']:
		fig.autofmt_xdate()
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


# 多个折线子图，用于呈现数据密集的情况
def multiplot(datasource):
	plt.close("all")
	seriescolor=["#04617B", "#F08300", "#81CDE4", "#739AAE", "#819933", "#E2D700", "#023A4A", "#904F00", "#2690B0", "#405E6E"]
	fig=plt.figure(figsize=(datasource['figure']['figsize']))
	label=datasource['Xaxis'][0]['axisLabel']['label']
	if datasource['Xaxis'][0]['wordnum']:
		label=[add_newline(i,datasource['Xaxis'][0]['wordnum']) for i in label]
	seriesnum=len(datasource['Yaxis'])
	texts=[]
	lines,labels=[],[]
	for i in range(seriesnum):
		plotid=str(seriesnum)+'1'+str(i+1)
		ax=fig.add_subplot(plotid)
		ax.plot(label,datasource['Yaxis'][i]['data'],label=datasource['Yaxis'][i]['seriesname'],
			color=seriescolor[i])
		if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
			for a, b in zip(label, datasource['Yaxis'][i]['data']):
				texts.append(ax.text(a, b, format(float(b), datasource['textstyle']['format']) + "%",
									 va=datasource['textstyle']['horizontalalignment'],
									 ha=datasource['textstyle']['verticalalignment']))
			def to_percent(y,pos):
				return "{0}{1}".format(datasource['Yaxis'][i]['axisLabel']['format'][1]%(y),"%")
			formatter=ticker.FuncFormatter(to_percent)
		else:
			for a, b in zip(label, datasource['Yaxis'][i]['data']):
				texts.append(ax.text(a, b, format(float(b), datasource['textstyle']['format']),
									 va=datasource['textstyle']['horizontalalignment'],
									 ha=datasource['textstyle']['verticalalignment']))
			formatter=ticker.FormatStrFormatter(datasource['Yaxis'][i]['axisLabel']['format'])
		ax.yaxis.set_major_formatter(formatter)
		axline,axlabel=ax.get_legend_handles_labels()
		lines.extend(axline)
		labels.extend(axlabel)
		ax.set_ylim(datasource['Yaxis'][i]['limit'])
		if i==seriesnum-1:
			ax.set_xticklabels(label)
		else:
			ax.set_xticklabels(())
	if datasource['autoadjust']['adjustText']:
			adjust_text(texts)
	if datasource['legend']['show']:
		fig.legend(lines, labels,
			loc=datasource['legend']['location'],
			ncol=eval(datasource['legend']['ncol']),
			frameon=datasource['legend']['frameon'])
	if datasource['autoadjust']['tight_layout']:
		fig.tight_layout()
	if datasource['autoadjust']['autofmt_xdate']:
		fig.autofmt_xdate()
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


# 饼图
def pie(datasource):
	plt.close("all")
	matplotlib.rcParams['font.size'] = datasource['figure']['fontsize']
	seriescolor = ["#3E8EB9", "#F08300", "#838B98", "#81CDE4", "#B1C7D2", "#91A64D", "#023A4A", "#904F00", "#2690B0",
				   "#405E6E"]
	fig = plt.figure()
	ax = fig.add_subplot()
	label = datasource['Xaxis'][0]['axisLabel']['label']
	value = datasource['Yaxis'][0]['data']
	labells = []
	for i in range(len(label)):
		lab = label[i]
		newlabel = '{},{:.2f}%'.format(lab, value[i])
		labells.append(newlabel)
	# wedges,texts,autotexts=ax.pie(x=value,
	wedges, texts = ax.pie(x=value,
						   labels=labells,
						   colors=seriescolor,
						   # autopct=datasource['pies']['autopct'],
						   radius=datasource['pies']['radius'],
						   pctdistance=datasource['pies']['pctdistance'],
						   startangle=datasource['pies']['startangle'],
						   shadow=datasource['pies']['shadow'],
						   wedgeprops=dict(width=datasource['pies']['wedgeprops']['width'],
										   edgecolor=datasource['pies']['wedgeprops']['edgecolor'])
						   )
	if datasource['autoadjust']['adjustText']:
		adjust_text(texts,
					autoalign=datasource['autoadjust']['autoalign'],
					only_move={"points": datasource['autoadjust']['only_move']['points'],
							   "text": datasource['autoadjust']['only_move']['text'],
							   "objects": datasource['autoadjust']['only_move']['objects']}
					)
	del_blank()
	if datasource['autoadjust']['tight_layout']:
		fig.tight_layout()
	if datasource['autoadjust']['autofmt_xdate']:
		fig.autofmt_xdate()
	fig.savefig(dpi=datasource['savefig']['dpi'], fname=datasource['savefig']['filename'] + '.png', transparent=True)
	# plt.show()


#多个系列饼图
def pies(datasource):
	plt.close("all")
	seriescolor=["#04617B", "#F08300", "#81CDE4", "#739AAE", "#819933", "#E2D700", "#023A4A", "#904F00", "#2690B0", "#405E6E"]
	fig=plt.figure()
	ax=fig.add_subplot()
	label=[datasource['Xaxis'][0]['axisLabel']['label'],None]
	seriesnum=len(datasource['Yaxis'])
	for i in range(seriesnum):
		value=datasource['Yaxis'][i]['data']
		wedges,texts,autotexts=ax.pie(x=value,
			# labels=label[i],
			colors=seriescolor,
			autopct=datasource['Yaxis'][i]['seriesname']+','+datasource['pies']['autopct'],
			radius=datasource['pies']['radius'][i],
			pctdistance=datasource['pies']['pctdistance'][i],
			startangle=datasource['pies']['startangle'],
			shadow=datasource['pies']['shadow'],
			wedgeprops=dict(width=datasource['pies']['wedgeprops']['width'],
				edgecolor=datasource['pies']['wedgeprops']['edgecolor']))
		if datasource['legend']['show'][i]:
			ax.legend(wedges,
				label[0],
				loc=datasource['legend']['location'],
				ncol=eval(datasource['legend']['ncol']),
				bbox_to_anchor=tuple(datasource['legend']['bbox_to_anchor']),
				frameon=datasource['legend']['frameon'])
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


#散点图
def scatter(datasource):
	plt.close("all")
	seriescolor=["#04617B", "#F08300", "#81CDE4", "#739AAE", "#819933", "#E2D700", "#023A4A", "#904F00", "#2690B0", "#405E6E"]
	fig=plt.figure()
	ax=fig.add_subplot()
	x=datasource['Xaxis'][0]['data']
	seriesnum=len(datasource['Yaxis'])
	for i in range(seriesnum):
		ax.scatter(x,datasource['Yaxis'][i]['data'],marker=datasource['marker']['marker'],
			color=seriescolor[i])
		if 'per' in datasource['Xaxis'][i]['axisLabel']['format']:
			def to_percent(y,pos):
				return "{0}{1}".format(datasource['Xaxis'][i]['axisLabel']['format'][1]%(y),"%")
			formatter=ticker.FuncFormatter(to_percent)
		else:
			formatter=ticker.FormatStrFormatter(datasource['Xaxis'][i]['axisLabel']['format'])
		ax.xaxis.set_major_formatter(formatter)
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


# 雷达图
def radar(datasource):
	plt.close("all")
	matplotlib.rcParams['font.size'] = datasource['figure']['fontsize']
	seriescolor=["#04617B", "#F08300", "#81CDE4", "#739AAE", "#819933", "#E2D700", "#023A4A", "#904F00", "#2690B0", "#405E6E"]
	seriesnum=len(datasource['Yaxis'])
	label=datasource['Xaxis'][0]['axisLabel']['label']
	dimnum=len(label)
	#ymin=float(min([min(datasource['Yaxis'][i]['data']) for i in range(seriesnum)]))
	#ymax=float(max([max(datasource['Yaxis'][i]['data']) for i in range(seriesnum)]))
	if str(datasource['range']['ymin']).find('Yaxis') > 0:
		ymin = float(min([min(datasource['Yaxis'][i]['data']) for i in range(seriesnum)]))
		ymax = float(max([max(datasource['Yaxis'][i]['data']) for i in range(seriesnum)]))
	else:
		ymin = float(eval(datasource['range']['ymin']))
		ymax = float(eval(datasource['range']['ymax']))
	angles0=np.linspace(0,2*np.pi,dimnum,endpoint=False)
	angles=np.concatenate((angles0,[angles0[0]]))
	fig=plt.figure()
	ax=fig.add_subplot(polar=True)
	gap=(ymax-ymin) / 2.0
	for i in np.arange(ymin,ymax+gap,gap):
		ax.plot(angles,[i]*(dimnum+1),lw=0.5,color='grey',alpha=0.8)
	# 绘制雷达图
	texts=[]
	for i in range(seriesnum):
		ydata0=datasource['Yaxis'][i]['data']
		ydata=np.concatenate((ydata0,[ydata0[0]]))
		# 标签
		labells = []
		for j in range(len(label)):
			newlabel = '{}\n{:.2f}'.format(label[j], ydata0[j])
			labells.append(newlabel)
		seriesname=''
		if 'seriesname' in datasource['Yaxis'][i].keys():
			seriesname=datasource['Yaxis'][i]['seriesname']
		color=seriescolor[i]
		ax.plot(angles, ydata,color=color,linewidth=datasource['lines']['linewidth'],
				linestyle=datasource['lines']['linestyle'][i],label=seriesname)
		ax.fill(angles, ydata, facecolor=color, alpha=0.6)
		for a, b, c in zip(angles0, ydata0, labells):
			texts.append(ax.text(a, b + 0.1, c))
	if datasource['autoadjust']['adjustText']:
		adjust_text(texts,
					autoalign=datasource['autoadjust']['autoalign'],
					only_move={"points": datasource['autoadjust']['only_move']['points'],
							   "text": datasource['autoadjust']['only_move']['text'],
							   "objects": datasource['autoadjust']['only_move']['objects']})
	ax.set_thetagrids(angles0*180/np.pi,label)
	ax.spines['polar'].set_visible(False)#不显示极坐标最外的圆形
	ax.set_theta_zero_location('N')#设置极坐标的起点（即0度）在正上方向
	ax.grid(False)# 不显示分隔线
	ax.set_yticks([]) # 不显示坐标间隔
	ax.set_xticks([])
	if datasource['legend']['show']:
		ax.legend(loc=datasource['legend']['location'],
				  ncol=eval(datasource['legend']['ncol']),
				  bbox_to_anchor=tuple(datasource['legend']['bbox_to_anchor']),
				  frameon=datasource['legend']['frameon'])
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


# 组合图
def plot_bar(datasource):
	plt.close("all")
	seriescolor=["#04617B", "#F08300", "#81CDE4", "#739AAE", "#819933", "#E2D700", "#023A4A", "#904F00", "#2690B0", "#405E6E"]
	fig=plt.figure()
	ax=fig.add_subplot()
	label=datasource['Xaxis'][0]['axisLabel']['label']
	if datasource['Xaxis'][0]['wordnum']:
		label=[add_newline(i,datasource['Xaxis'][0]['wordnum']) for i in label]
	x=np.arange(len(label))
	seriesnum=len(datasource['Yaxis'])
	barnum=[i['type'] for i in datasource['Yaxis']].count('bar')
	bar_width=0.6/barnum
	texts=[]
	lines,labels=[],[]
	for i in range(seriesnum):
		ytype=datasource['Yaxis'][i]['type']
		ydata=datasource['Yaxis'][i]['data']
		seriesname=datasource['Yaxis'][i]['seriesname']
		color=seriescolor[i]
		if ytype=='bar':
			ax.bar(x+i*bar_width,ydata,width=bar_width,label=seriesname,color=color)
			if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
				for a,b in zip(x+i*bar_width,datasource['Yaxis'][i]['data']):
					texts.append(ax.text(a,b,format(float(b),datasource['textstyle']['format'][i]) + "%",
					va=datasource['Yaxis'][i]['axisLabel']['verticalalignment'],
					ha=datasource['Yaxis'][i]['axisLabel']['horizontalalignment']))
			else:
				for a, b in zip(x + i * bar_width, datasource['Yaxis'][i]['data']):
					texts.append(ax.text(a, b, format(float(b), datasource['textstyle']['format'][i]),
										 va=datasource['Yaxis'][i]['axisLabel']['verticalalignment'],
										 ha=datasource['Yaxis'][i]['axisLabel']['horizontalalignment']))
			axline,axlabel=ax.get_legend_handles_labels()
			lines.extend(axline)
			labels.extend(axlabel)
			if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
				def to_percent(y,pos):
					return "{0}{1}".format(datasource['Yaxis'][i]['axisLabel']['format'][1]%(y),"%")
				formatter=ticker.FuncFormatter(to_percent)
			else:
				formatter=ticker.FormatStrFormatter(datasource['Yaxis'][i]['axisLabel']['format'])
			ax.yaxis.set_major_formatter(formatter)
			ax.set_ylim(datasource['Yaxis'][i]['limit'])
		elif ytype=='plot':
			ax2=ax.twinx()
			ax2.plot(x+bar_width*((barnum-1)/2),ydata,label=seriesname,color=color)
			if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
				for a,b in zip(x+bar_width*((barnum-1)/2),datasource['Yaxis'][i]['data']):
					texts.append(ax2.text(a,b,format(float(b),datasource['textstyle']['format'][i]) + "%",
					ha=datasource['Yaxis'][i]['axisLabel']['horizontalalignment'],
					va=datasource['Yaxis'][i]['axisLabel']['verticalalignment']))
			else:
				for a,b in zip(x+bar_width*((barnum-1)/2),datasource['Yaxis'][i]['data']):
					texts.append(ax2.text(a,b,format(float(b),datasource['textstyle']['format'][i]),
					ha=datasource['Yaxis'][i]['axisLabel']['horizontalalignment'],
					va=datasource['Yaxis'][i]['axisLabel']['verticalalignment']))
			axline,axlabel=ax2.get_legend_handles_labels()
			lines.extend(axline)
			labels.extend(axlabel)
			if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
				def to_percent(y,pos):
					return "{0}{1}".format(datasource['Yaxis'][i]['axisLabel']['format'][1]%(y),"%")
				formatter=ticker.FuncFormatter(to_percent)
			else:
				formatter=ticker.FormatStrFormatter(datasource['Yaxis'][i]['axisLabel']['format'])
			ax2.yaxis.set_major_formatter(formatter)
			ax2.set_ylim(datasource['Yaxis'][i]['limit'])
	if datasource['autoadjust']['adjustText']:
		adjust_text(texts)
	if datasource['legend']['show']:
		fig.legend(lines, labels,
			loc=datasource['legend']['location'],
			ncol=eval(datasource['legend']['ncol']),
			frameon=datasource['legend']['frameon'])
	ax.set_xticks(x+bar_width*((barnum-1)/2))
	ax.set_xticklabels(label)
	ax2.spines['right'].set_visible(True)
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


# 地图底图+饼图+柱状图
def pic_pie_bar(datasource):
	plt.close("all")
	seriescolor=["#04617B", "#F08300", "#81CDE4", "#739AAE", "#819933", "#E2D700", "#023A4A", "#904F00", "#2690B0", "#405E6E"]
	fig=plt.figure()
	ax=fig.add_subplot()
	current_path=os.getcwd()
	with cbook.get_sample_data(current_path+'\\china_map.png') as image_file:
		image = plt.imread(image_file)
	im=ax.imshow(image,alpha=0.3)
	ax.axis('off')
	seriesnum=len(datasource['Yaxis'])
	texts=[]
	for i in range(seriesnum):
		label=datasource['Xaxis'][i]['axisLabel']['label']
		ytype=datasource['Yaxis'][i]['type']
		ydata=datasource['Yaxis'][i]['data']
		if ytype=="bar":
			ax1=fig.add_subplot(facecolor=(1,1,1,0))
			barnum=[i['type'] for i in datasource['Yaxis']].count('bar')
			bar_width=0.6/barnum
			if datasource['Xaxis'][i]['wordnum']:
				label=[add_newline(i,datasource['Xaxis'][0]['wordnum']) for i in label]
			x=np.arange(len(label))
			ax1.bar(x+i*bar_width,ydata,width=bar_width,color=seriescolor[i])
			if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
				for a,b in zip(x+i*bar_width,ydata):
					texts.append(ax1.text(a,b,format(float(b),datasource['textstyle']['format']) + "%",
					ha=datasource['Yaxis'][i]['axisLabel']['horizontalalignment'],
					va=datasource['Yaxis'][i]['axisLabel']['verticalalignment']))
			else:
				for a,b in zip(x+i*bar_width,ydata):
					texts.append(ax1.text(a,b,format(float(b),datasource['textstyle']['format']),
					ha=datasource['Yaxis'][i]['axisLabel']['horizontalalignment'],
					va=datasource['Yaxis'][i]['axisLabel']['verticalalignment']))
			formatter=ticker.FormatStrFormatter(datasource['Yaxis'][i]['axisLabel']['format'])
			ax1.yaxis.set_major_formatter(formatter)
			ax1.set_xticks(x+bar_width*((barnum-1)/2))
			ax1.set_xticklabels(label)
			if 'per' in datasource['Yaxis'][i]['axisLabel']['format']:
				def to_percent(y,pos):
					return "{0}{1}".format(datasource['Yaxis'][i]['axisLabel']['format'][1]%(y),"%")
				formatter=ticker.FuncFormatter(to_percent)
			else:
				formatter=ticker.FormatStrFormatter(datasource['Yaxis'][i]['axisLabel']['format'])
			ax1.yaxis.set_major_formatter(formatter)
		elif ytype=="pie":
			ax2=fig.add_axes([0.3,0.3,0.5,0.5])
			label=datasource['Xaxis'][i]['axisLabel']['label']
			value=datasource['Yaxis'][i]['data']
			wedges,texts,autotexts=ax2.pie(x=value,
				labels=label,
				colors=seriescolor,
				autopct=datasource['pies']['autopct'],
				radius=datasource['pies']['radius'],
				pctdistance=datasource['pies']['pctdistance'],
				startangle=datasource['pies']['startangle'],
				shadow=datasource['pies']['shadow'],
				wedgeprops=dict(width=datasource['pies']['wedgeprops']['width'],
					edgecolor=datasource['pies']['wedgeprops']['edgecolor']))
	if datasource['autoadjust']['adjustText']:
		adjust_text(texts)
	if datasource['legend']['show']:
		ax.legend(loc=datasource['legend']['location'],
			ncol=eval(datasource['legend']['ncol']),
			bbox_to_anchor=tuple(datasource['legend']['bbox_to_anchor']),
			frameon=datasource['legend']['frameon'])
	if datasource['autoadjust']['tight_layout']:
		fig.tight_layout()
	if datasource['autoadjust']['autofmt_xdate']:
		fig.autofmt_xdate()
	if "bbox_inches" in datasource['savefig'].keys():
		fig.savefig(dpi=datasource['savefig']['dpi'], bbox_inches=datasource['savefig']['bbox_inches'],
					pad_inches=datasource['savefig']['pad_inches'], fname=datasource['savefig']['filename'] + '.png')
	else:
		fig.savefig(dpi=datasource['savefig']['dpi'],fname=datasource['savefig']['filename']+'.png')
	#plt.show()


# 地图
def pic_map(datasource):
	areas=datasource['Xaxis'][0]['axisLabel']['label']
	values=datasource['Yaxis'][0]['data']
	#排序
	data_sort=[list(z) for z in zip(areas, values)]
	data_sort.sort(key=lambda x:(x[1]),reverse=True)
	areas=[x[0] for x in data_sort]
	values=[x[1] for x in data_sort]
	map_chart=Map()
	map_chart.add(series_name='',
		data_pair=[list(z) for z in zip(areas, values)],
		maptype='china',
		is_map_symbol_show=False)
	map_chart.set_series_opts(label_opts=opts.LabelOpts(is_show=False,font_size=9))
	map_chart.set_global_opts(visualmap_opts=opts.VisualMapOpts(is_calculable=True,dimension=0,
		min_=min(values),
		max_=max(values),
		pos_right='100',
		pos_top='center',
		range_text=[datasource['Yaxis'][0]['seriesname'],''],
		range_color=["#04617B", "#C0C9CE"][::-1],
		textstyle_opts=opts.TextStyleOpts(font_size=10)))
	bar=Bar()
	bar.add_xaxis(xaxis_data=areas)
	bar.add_yaxis(series_name="",
		yaxis_data=values,
		yaxis_index=1,
		label_opts=opts.LabelOpts(is_show=True,position='right',formatter='{b}:{c}',font_size=9))
	bar.reversal_axis()
	bar.set_global_opts(
				xaxis_opts=opts.AxisOpts(is_show=False,axislabel_opts=opts.LabelOpts(is_show=False)),#不显示x轴及标签
				yaxis_opts=opts.AxisOpts(is_show=True,is_inverse=True,axislabel_opts=opts.LabelOpts(is_show=False),#不显示y轴标签
					axistick_opts=opts.AxisTickOpts(is_show=False), #不显示y轴tick
					axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts(color='rgba(0,0,0,0.5)'))), #y轴线设置
				visualmap_opts=opts.VisualMapOpts(is_calculable=True,dimension=0,#设置dimension，条形图每个itme和visualmap对应
		min_=min(values),
		max_=max(values),
		pos_right='100',
		pos_top='center',
		range_color=["#04617B", "#C0C9CE"][::-1],
		range_text=[datasource['Yaxis'][0]['seriesname'],''],
		textstyle_opts=opts.TextStyleOpts(font_size=10)))
	# 组合图
	grid_chart=Grid()
	grid_chart.add(bar, grid_opts=opts.GridOpts( pos_left="10", pos_right="80%", pos_top="70%", pos_bottom="5",
												 is_contain_label=False))
	grid_chart.add(map_chart,grid_opts=opts.GridOpts())

	# grid_chart.render()
	make_snapshot(snapshot, grid_chart.render(), datasource['savefig']['filename']+'.png')


# 象形柱状图
def pictorial_bar_horizon2(datasource):
	with open("symbol.json", "r", encoding="utf-8") as f:
		symbols = json.load(f)
	#作图
	seriescolor=["#04617B", "#F08300", "#81CDE4", "#739AAE", "#819933", "#E2D700", "#023A4A", "#904F00", "#2690B0", "#405E6E"]
	label=datasource['Xaxis'][0]['axisLabel']['label']
	if datasource['Xaxis'][0]['wordnum']:
		label=[add_newline(i,datasource['Xaxis'][0]['wordnum']) for i in label]
	seriesnum=len(datasource['Yaxis'])
	pictorialbar=PictorialBar()
	pictorialbar.add_xaxis(label)
	for i in range(seriesnum):
		if seriesnum>1:
			legendname=datasource['Yaxis'][i]['seriesname']
		else:
			legendname=""
		ydata=datasource['Yaxis'][i]['data']
		pictorialbar.add_yaxis(legendname,
			ydata,
			label_opts=opts.LabelOpts(position=datasource['Yaxis'][i]['axisLabel']['position'],
				formatter='{c}',
				font_size=15),
			symbol_size=20,
			color=seriescolor[i],
			symbol_repeat='fixed',
			symbol_offset=[0,datasource['Yaxis'][i]['axisLabel']['offset']],
			is_symbol_clip=True,
			symbol='path://'+symbols[datasource['Yaxis'][i]['symbol']]
			)
	if datasource['Xaxis'][0]['reverse_axis']:
		pictorialbar.reversal_axis()
	pictorialbar.set_global_opts(
			xaxis_opts=opts.AxisOpts(is_show=False),
			yaxis_opts=opts.AxisOpts(
				axislabel_opts=opts.LabelOpts(font_size=15),
				axistick_opts=opts.AxisTickOpts(is_show=False),
				axisline_opts=opts.AxisLineOpts(
					linestyle_opts=opts.LineStyleOpts(opacity=0))))
	# pictorialbar.render()
	make_snapshot(snapshot, pictorialbar.render(),datasource['savefig']['filename']+'.png')

############################################################作图
#设置字体、图形样式
#filePath = os.path.abspath(os.curdir).replace('core', 'docx')
#filePath = os.path.join(filePath, 'charts', 'simhei.ttf')
#prop = font_manager.FontProperties(fname=filePath)
#matplotlib.rcParams['font.family'] = prop.get_name()
#matplotlib.rcParams['font.family']='sans-serif'
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
matplotlib.rcParams['axes.unicode_minus'] = False
matplotlib.rcParams['axes.spines.top'] = 0
matplotlib.rcParams['axes.spines.right'] = 0

############################################################柱状图
