def _render_as_image(self, file_type): """ This is an internal function to serve _repr_jpeg_, _repr_png_ and _repr_svg_. :param file_type: the parameter is mostly image file types. """ if CURRENT_CONFIG.jupyter_presentation != file_type: return None if self.renderer == constants.SVG_RENDERER: if file_type != constants.SVG: raise exceptions.InvalidConfiguration( "svg renderer produces only svg image." ) elif file_type not in [constants.JPEG, constants.PNG]: # CANVAS_RENDERER here raise exceptions.InvalidConfiguration( "svg output requires svg renderer." ) env = engine.create_default_environment(file_type) outfile = "tmp." + file_type content = env.render_chart_to_file( chart=self, path=outfile, verbose=False ) if content: os.unlink(outfile) return content
def render_embed(self): """ 渲染图表的所有配置项,为 web pages 服务,不过需先提供所需要的js 依赖文件 """ env = engine.create_default_environment(constants.DEFAULT_HTML) html = env.render_container_and_echarts_code(self) return Markup(html)
def _repr_html_(self): """ :return: html content for jupyter """ dependencies = self.js_dependencies require_config = CURRENT_CONFIG.produce_require_configuration( dependencies ) config_items = require_config["config_items"] libraries = require_config["libraries"] env = engine.create_default_environment(constants.DEFAULT_HTML) return env.render_chart_to_notebook( charts=self, config_items=config_items, libraries=libraries )
def render( self, path="render.html", template_name="simple_chart.html", object_name="chart", **kwargs ): _, ext = os.path.splitext(path) _file_type = ext[1:] env = engine.create_default_environment(_file_type) env.render_chart_to_file( chart=self, object_name=object_name, path=path, template_name=template_name, **kwargs )
def render(self, path="render.html", template_name="simple_page.html", object_name="page", **kwargs): _, ext = os.path.splitext(path) _file_type = ext[1:] if _file_type != constants.DEFAULT_HTML: raise NotImplementedError( "Rendering Page instance as image is not supported!") env = engine.create_default_environment(constants.DEFAULT_HTML) env.render_chart_to_file(chart=self, object_name=object_name, path=path, template_name=template_name, **kwargs)
def _repr_html_(self): """ 渲染配置项并将图形显示在 notebook 中 chart/page => charts chart.js_dependencies => require_config => config_items, libraries :return A unicode string. """ if CURRENT_CONFIG.jupyter_presentation != constants.DEFAULT_HTML: return None require_config = CURRENT_CONFIG.produce_require_configuration( self.js_dependencies) config_items = require_config["config_items"] libraries = require_config["libraries"] env = engine.create_default_environment(constants.DEFAULT_HTML) return env.render_chart_to_notebook(charts=(self, ), config_items=config_items, libraries=libraries)
def _repr_html_(self): """ 渲染配置项并将图形显示在 notebook 中 chart/page => charts chart.js_dependencies => require_config => config_items, libraries :return A unicode string. """ if CURRENT_CONFIG.jupyter_presentation != constants.DEFAULT_HTML: return None require_config = CURRENT_CONFIG.produce_require_configuration( self.js_dependencies ) config_items = require_config["config_items"] libraries = require_config["libraries"] env = engine.create_default_environment(constants.DEFAULT_HTML) return env.render_chart_to_notebook( charts=(self,), config_items=config_items, libraries=libraries )
def render( self, path="render.html", template_name="simple_page.html", object_name="page", **kwargs ): _, ext = os.path.splitext(path) _file_type = ext[1:] if _file_type != constants.DEFAULT_HTML: raise NotImplementedError( "Rendering Page instance as image is not supported!" ) env = engine.create_default_environment(constants.DEFAULT_HTML) env.render_chart_to_file( chart=self, object_name=object_name, path=path, template_name=template_name, **kwargs )
from pyecharts import Bar from pyecharts.engine import create_default_environment title = 'bar chart' index = pd.date_range('7/11/2018', periods=6, freq='M') df1 = pd.DataFrame(np.random.randn(6), index=index) df2 = pd.DataFrame(np.random.randn(6), index=index) print(index) print(df1.values) dtvalue1 = [i[0] for i in df1.values] dtvalue2 = [i[0] for i in df2.values] print(df1.index) bar = Bar(title, 'Profit and loss situation') #提供更多使用工具 is_more_utils=True #is_convert x轴和y轴转换 bar.add('Profit', index, dtvalue1, is_more_utils=True, is_legend_show=True, is_convert=True, is_stack=True) bar.add('loss', index, dtvalue1, is_convert=True, is_stack=True) env = create_default_environment('png') bar.render(path=r'E:\python_project\pyecharts\ex2.html')
def drawing(chart, path, filet_type='html'): env = create_default_environment(filet_type) # create_default_environment(filet_type) # file_type: 'html', 'svg', 'png', 'jpeg', 'gif' or 'pdf' env.render_chart_to_file(chart, path=path)
def create_charts(): page = Page() #饼形图 attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"] v1 = [11, 12, 13, 10, 10, 10] chart = Pie("饼图示例1") chart.add("", attr, v1, is_label_show=True) #chart.render() page.add(chart) #1.第一个示例 bar = Bar("我的第一个图表1", "这里是副标题") #主要方法,用于添加图表的数据和设置各种配置项 bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], \ [5, 20, 36, 10, 75, 90]) # 该行只为了打印配置项,方便调试时使用 bar.print_echarts_options() # 生成本地 HTML 文件 #默认将会在根目录下生成一个 render.html 的文件,支持 path 参数,设置文件保存位置, # 如 render(r"e:\my_first_chart.html"),文件用浏览器打开。 bar.render(r'我的第一个图表.html') #使用Page类,将图表加入到对象中 page.add(bar) #2.如果想要提供更多实用工具按钮,请在 add() 中设置 is_more_utils 为 True bar = Bar("我的第一个图表2", "这里是副标题") bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90], is_more_utils=True) #bar.render() page.add(bar) #3.使用主题 bar = Bar("我的第一个图表3", "这里是副标题") bar.use_theme('dark') bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], \ [5, 20, 36, 10, 75, 90]) #bar.render() page.add(bar) #4.使用 pyecharts-snapshot 插件--直接保存为图片, # 文件结尾可以为 svg/jpeg/png/pdf/gif。 # 请注意,svg 文件需要你在初始化 bar 的时候设置 renderer='svg'。 bar = Bar("我的第一个图表4", "这里是副标题") bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90]) bar.render(path=r'我的第一个图表.gif') #page.add(bar) #5.多次显示图表 bar = Bar("我的第一个图表5", "这里是副标题") bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90]) line = Line("我的第一个图表", "这里是副标题") line.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90]) env = create_default_environment("html") # 为渲染创建一个默认配置环境 # create_default_environment(filet_ype) # file_type: 'html', 'svg', 'png', 'jpeg', 'gif' or 'pdf' env.render_chart_to_file(bar, path='bar.html') env.render_chart_to_file(line, path='line.html') return page
from pyecharts import Bar, Line from pyecharts.engine import create_default_environment bar = Bar("我的第一个图表", "这里是副标题") bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90]) line = Line("我的第一个图表", "这里是副标题") line.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90]) env = create_default_environment("html") env.render_container_and_echarts_code(line) env.render_container_and_echarts_code(bar) print(env.render_container_and_echarts_code(bar)) window['myChart_'+] %hist
print(df[['area', 'city']]) #城市分布 city_count = df.groupby('city')['city'].count().sort_values(ascending=False) print(city_count) #柱状图分析 bar = Bar("城市分布") bar.add( "城市", city_count.index[:30], #取前三十个数据 city_count.values[:30], #取前三十个数据 is_label_show=True, xaxis_interval=0, xaxis_rotate=-45) env = create_default_environment('html') env.render_chart_to_file(bar, path='bar.html') # #组合成元祖,方便后续地图可视化传入数据 # city_data=list(zip(city_count.index,city_count.values)) # print(city_data) # # #地理坐标系Geo # geo=Geo('城市分布情况','data from SinaNews',title_color='#fff',title_pos='center', # width=800,height=600,background_color='#404a59') # attr,value=geo.cast(city_data) # geo.add( # '', # attr, # value, # visual_range=[0,360],
line_opacity="80%", xaxis_label_textsize=18, yaxis_label_textsize=18, xaxis_name_size=18, yaxis_name_size=18, xaxis_name_gap=30, yaxis_name_gap=80, xaxis_name_pos="center", yaxis_name_pos="middle", xaxis_line_width=2, yaxis_line_width=2, xaxis_splitline_show=False, yaxis_splitline_show=False, is_splitline_show=False, symbol_size=15, is_datazoom_show=args.zoom, ) for key in xdata: scatter.add(key, xdata[key], ydata[key], xaxis_max=args.xmax, yaxis_max=args.ymax, xaxis_name=xaxis_name, yaxis_name=yaxis_name, **s_style) grid.add(scatter, grid_bottom="20%") env = create_default_environment(args.type) env.render_chart_to_file(grid, path=args.outfile)
import json from pyecharts import Line, Bar, Pie, EffectScatter from pyecharts.engine import create_default_environment #from snapshot_selenium import snapshot as driver #from pyecharts.render import make_snapshot attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"] v1 = [5, 20, 36, 10, 10, 100] v2 = [55, 60, 16, 20, 15, 80] line = Line('折线图') line.add('商家A', attr, v1, mark_point=['max']) line.add('商家B', attr, v2, mark_point=['min'], is_smooth=True) #line.show_config() env = create_default_environment("png") env.render_chart_to_file(line, path='line.png') #line.render(path='./test.html')
def analyse(calculate_word_cloud=True): """ 分析 data.db -> user 的用户数据。 :param calculate_word_cloud: 是否计算词云,这个比较花费时间。 :return: """ conn = sqlite3.connect('data.db') cursor = conn.cursor() cursor.execute('SELECT * FROM user') data = cursor.fetchall() # 为渲染创建一个默认配置环境 # create_default_environment(filet_ype) # file_type: 'html', 'svg', 'png', 'jpeg', 'gif' or 'pdf' env = create_default_environment("html") # 1. gender gender_dict = {'male': 0, 'female': 0, 'unknown': 0} for x in data: if x[3] == 'male': gender_dict['male'] += 1 elif x[3] == 'female': gender_dict['female'] += 1 else: gender_dict['unknown'] += 1 print( "There are {} male users, {} female users, and {} users gender unknown." .format(gender_dict['male'], gender_dict['female'], gender_dict['unknown'])) attr1 = ['Male', 'Female', 'unknown'] v1 = [gender_dict['male'], gender_dict['female'], gender_dict['unknown']] gender = Pie("性别") gender.add("", attr1, v1, is_label_show=True) env.render_chart_to_file(gender, path='./html_files/gender.html') print( '-----------------------------------------------------------------------------------' ) # 2. 地区 region_dict = dict() for x in data: if x[6] in region_dict.keys(): region_dict[x[6]] += 1 else: region_dict[x[6]] = 1 region_list = [(k, v) for k, v in region_dict.items()] region_list = sorted(region_list, key=lambda x: x[1], reverse=True) print('Top30 region count: ') for i in range(30): if region_list[i][0]: print(region_list[i][0], end=',') print(region_list[i][1]) else: print('None', end=',') print(region_list[i][1]) style = Style(width=1100, height=600) # 1是中国数据,2是世界数据 china_data_dict = dict() v1 = list() v2 = list() a1 = list() a2 = list() # 国家名字典 country_name_dict = { '西班牙': 'Spain', '英国': 'United Kingdom', '美国': 'United States', '俄罗斯': 'Russia', '意大利': 'Italy', '加拿大': 'Canada', '澳大利亚': 'Australia', '日本': 'Japan', '法国': 'France', '韩国': 'Korea', '巴西': 'Brazil', '新加坡': 'Singapore', '马来西亚': 'Malaysia', '泰国': 'Thailand', '中国': 'China', '其他': 'Unknown Country' } for item in region_list: if item[0]: x = item[0].split() if x[0] != '海外': if x[0] in china_data_dict.keys(): china_data_dict[x[0]] += item[1] else: china_data_dict[x[0]] = item[1] else: if x[1] != '其他': a2.append(country_name_dict.get(x[1], x[1])) v2.append(item[1]) for k, v in china_data_dict.items(): a1.append(k) v1.append(v) # 加上中国的数据 # a2.append('China') # v2.append(sum(v1)) # 归一化到 0 - 100 def normalize(l): m = min(l) l = [x - m for x in l] m = max(l) l = [x / m * 100 for x in l] return l v1 = normalize(v1) v2 = normalize(v2) # 输出html chart = Map("国内懂球帝分布", **style.init_style) chart.add("", a1, v1, maptype='china', is_visualmap=True, visual_text_color='#000') env.render_chart_to_file(chart, path='./html_files/china_distribution.html') # 输出html chart = Map("海外懂球帝分布", **style.init_style) chart.add("", a2, v2, maptype='world', is_visualmap=True, visual_text_color='#000') env.render_chart_to_file(chart, path='./html_files/world_distribution.html') print( '-----------------------------------------------------------------------------------' ) # 3. 联赛 process_league_data('国家队', cursor, data, env) process_league_data('中超', cursor, data, env) process_league_data('英超', cursor, data, env) process_league_data('西甲', cursor, data, env) process_league_data('意甲', cursor, data, env) process_league_data('德甲', cursor, data, env) process_league_data('法甲', cursor, data, env) process_league_data('国内', cursor, data, env) process_league_data('俱乐部', cursor, data, env, figure_type='bar', limit=20) print( '-----------------------------------------------------------------------------------' ) # 4. name word cloud if calculate_word_cloud: name_list = [x[2] for x in data] jieba.load_userdict('dict.txt') cut_name_list = [jieba.cut(x, cut_all=False) for x in name_list] # cut_name_list = [jieba.cut_for_search(x) for x in name_list] #加载停用词表 stop = [line.strip() for line in open('stop_words.txt').readlines()] word_dict = dict() for cut_name in cut_name_list: for word in cut_name: if word not in stop: if word in word_dict.keys(): word_dict[word] += 1 else: word_dict[word] = 1 value_list = [(k, v) for k, v in word_dict.items()] value_list = sorted(value_list, key=lambda x: x[1], reverse=True) # 去掉单字 attr = [x[0] for x in value_list if len(x[0]) > 1] value = [x[1] for x in value_list if len(x[0]) > 1] # 取 top 100 attr = attr[:100] value = value[:100] wordcloud = WordCloud(width=1300, height=620) wordcloud.add("", attr, value, word_size_range=[20, 100]) env.render_chart_to_file(wordcloud, path='./html_files/word_cloud.html') print( '-----------------------------------------------------------------------------------' ) # 5. 加入时间 join_time = [int(x[8][6:-1]) for x in data if x[8][6:-1]] join_time_dict = dict() for x in join_time: if x in join_time_dict.keys(): join_time_dict[x] += 1 else: join_time_dict[x] = 1 join_time_list = [(k, v) for k, v in join_time_dict.items()] join_time_list = sorted(join_time_list, key=lambda x: x[0]) attr = [x[0] for x in join_time_list] v = [x[1] for x in join_time_list] t = datetime.datetime(2018, 5, 12) attr = [t - datetime.timedelta(days=x) for x in attr] attr = [f'{x.year}-{x.month}-{x.day}' for x in attr] bar = Bar(f"加入时间") bar.add("", attr, v, is_stack=True) env.render_chart_to_file(bar, path='./html_files/join_time.html') print( '-----------------------------------------------------------------------------------' ) # 6. post times post_time = [int(x[10]) for x in data if x[10] and int(x[10]) >= 0] post_time_dict = dict() for x in post_time: if x in post_time_dict.keys(): post_time_dict[x] += 1 else: post_time_dict[x] = 1 post_time_list = [(k, v) for k, v in post_time_dict.items()] post_time_list = sorted(post_time_list, key=lambda x: x[0]) attr = [x[0] for x in post_time_list] v = [x[1] for x in post_time_list] bar = Bar(f"Post times") bar.add("", attr, v, is_stack=True) env.render_chart_to_file(bar, path='./html_files/post_times.html') print( '-----------------------------------------------------------------------------------' ) # 6. reply times reply_time = [int(x[11]) for x in data if x[11] and int(x[11]) >= 0] reply_time_dict = dict() for x in reply_time: if x in reply_time_dict.keys(): reply_time_dict[x] += 1 else: reply_time_dict[x] = 1 reply_time_list = [(k, v) for k, v in reply_time_dict.items()] reply_time_list = sorted(reply_time_list, key=lambda x: x[0]) attr = [x[0] for x in reply_time_list] v = [x[1] for x in reply_time_list] bar = Bar(f"Reply times") bar.add("", attr, v, is_stack=True) env.render_chart_to_file(bar, path='./html_files/reply_times.html') print( '-----------------------------------------------------------------------------------' ) cursor.close() conn.commit() conn.close()
def report(request, year, user): year = year or datetime.datetime.now().year year = int(year) # 使用info存储整年和每月的数据 info = [] # 从 0 月(一整年) 到 12 月的数据 for month in range(13): info.append(get_report_data(user, year, month)) months = ['全年'] + [str(x) + "月" for x in range(1, 13)] charts = [] # 收治情况 charts.append(Bar("%d年收治" % (year), "每月收治人数")) charts[-1].add("收治人数", months[1:], [monthData['entry__sum'] for monthData in info[1:]]) # 床位日 charts.append(Bar("%d年床位日" % (year), "每月床位日")) charts[-1].add("床位日", months[1:], [monthData['total__sum'] for monthData in info[1:]]) # 收治率(大概率) charts.append(Bar("%d年" % (year), "每月统计率%")) charts[-1].add("ApacheII评分≥15分收治率", months, [monthData['apacheII15Rate'] for monthData in info]) charts[-1].add("预计病死率", months, [monthData['apacheIIDeathRate'] for monthData in info]) charts[-1].add("标化病死率", months, [monthData['standDeathRate'] for monthData in info]) # 收治率 charts.append(Bar("%d年" % (year), "每月统计率%")) charts[-1].add("治疗性抗生素标本送检率", months, [monthData['sampleRate'] for monthData in info]) charts[-1].add("深静脉血栓预防率", months, [monthData['preventDVTRate'] for monthData in info]) charts[-1].add("3hBundle完成率", months, [monthData['bundle3Rate'] for monthData in info]) charts[-1].add("6hBundle完成率", months, [monthData['bundle6Rate'] for monthData in info]) # 收治率(小概率) charts.append(Bar("%d年" % (year), "每月统计率%")) charts[-1].add( "非计划气管插管拨管率", months, [monthData['unplannedExtubationRate'] for monthData in info]) charts[-1].add("48h再插管率", months, [monthData['reintubationRate'] for monthData in info]) charts[-1].add("非计划术后入ICU率", months, [monthData['unplannedShiftRate'] for monthData in info]) charts[-1].add("48小时后重返ICU率", months, [monthData['revertRate'] for monthData in info]) # 三管监测(小概率) charts.append(Bar("%d年" % (year), "每月统计率‰")) charts[-1].add("VAP发生率", months, [monthData['VAPRate'] for monthData in info]) charts[-1].add("CRBSI发生率", months, [monthData['CRBSIRate'] for monthData in info]) charts[-1].add("CAUTI发生率", months, [monthData['CAUTIRate'] for monthData in info]) # 为渲染创建一个默认配置环境 env = create_default_environment("html") echarts = [] for chart in charts: echarts.append(env.render_container_and_echarts_code(chart=chart)) template = "icu/tools/qualityControl/report.html" return render(request, template, { 'user': user, 'info': info, 'echarts': echarts })