def test_grid_add_overlap(): from pyecharts import Overlap grid = Grid() attr = ["{}月".format(i) for i in range(1, 13)] v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] v3 = [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2] bar = Bar("Overlap+Grid 示例", width=1200, height=600, title_pos="40%") bar.add("蒸发量", attr, v1) bar.add( "降水量", attr, v2, yaxis_formatter=" ml", yaxis_max=250, legend_pos="85%", legend_orient="vertical", legend_top="45%", ) line = Line() line.add("平均温度", attr, v3, yaxis_formatter=" °C") overlap = Overlap() overlap.add(bar) overlap.add(line, is_add_yaxis=True, yaxis_index=1) grid.add(overlap, grid_right="20%") grid.render()
def ax_draw_macd(axes, kdata, n1=12, n2=26, n3=9): """绘制MACD :param axes: 指定的坐标轴 :param KData kdata: KData :param int n1: 指标 MACD 的参数1 :param int n2: 指标 MACD 的参数2 :param int n3: 指标 MACD 的参数3 """ macd = MACD(CLOSE(kdata), n1, n2, n3) bmacd, fmacd, smacd = macd.getResult(0), macd.getResult(1), macd.getResult(2) text = 'MACD(%s,%s,%s) DIF:%.2f, DEA:%.2f, BAR:%.2f'%(n1,n2,n3,fmacd[-1],smacd[-1],bmacd[-1]) #axes.text(0.01,0.97, text, horizontalalignment='left', verticalalignment='top', transform=axes.transAxes) total = len(kdata) x_list = [i for i in range(total)] y1_list = [round(x) if x > 0 else '-' for x in bmacd] y2_list = [round(x) if x <= 0 else '-' for x in bmacd] style = gcf().get_style(axes) bar = Bar(subtitle=text, title_pos='10%', title_top='8%') bar.add('1', x_list, y1_list, is_stack=True, is_legend_show=False, **style) bar.add('2', x_list, y2_list, is_stack=True, is_legend_show=False, **style) axes.add(bar) fmacd.plot(axes=axes, line_type='dotted') smacd.plot(axes=axes) gcf().add_axis(axes) return gcf()
def test_timeline_label_color(): attr = ["{}月".format(i) for i in range(1, 7)] bar = Bar("1 月份数据", "数据纯属虚构") bar.add( "bar", attr, [randint(10, 50) for _ in range(6)], label_color=["red", "#213", "black"], ) line = Line() line.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_0 = Overlap() overlap_0.add(bar) overlap_0.add(line) bar_1 = Bar("2 月份数据", "数据纯属虚构") bar_1.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_1 = Line() line_1.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_1 = Overlap() overlap_1.add(bar_1) overlap_1.add(line_1) timeline = Timeline(timeline_bottom=0) timeline.add(overlap_0, "1 月") timeline.add(overlap_1, "2 月") content = timeline._repr_html_() assert '"color": [' in content assert "red" in content assert "#213" in content assert "black" in content
def test_grid_top_bottom(): v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] bar = Bar("柱状图示例", height=720) bar.add("商家A", CLOTHES, v1, is_stack=True) bar.add("商家B", CLOTHES, v2, is_stack=True) line = Line("折线图示例", title_top="50%") line.add( "最高气温", WEEK, [11, 11, 15, 13, 12, 13, 10], mark_point=["max", "min"], mark_line=["average"], ) line.add( "最低气温", WEEK, [1, -2, 2, 5, 3, 2, 0], mark_point=["max", "min"], mark_line=["average"], legend_top="50%", ) grid = Grid() grid.add(bar, grid_bottom="60%") grid.add(line, grid_top="60%") grid.render()
def test_bar_stack(): bar = Bar("柱状图数据堆叠示例") bar.add("商家A", CLOTHES, clothes_v1, is_stack=True) bar.add("商家B", CLOTHES, clothes_v2, is_stack=True) html_content = bar._repr_html_() assert "dataZoom" not in html_content assert "stack_" in html_content
def create_three(): page = Page(page_title=TEST_PAGE_TITLE) # bar v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] bar = Bar("柱状图数据堆叠示例") bar.add("商家A", CLOTHES, v1, is_stack=True) bar.add("商家B", CLOTHES, v2, is_stack=True) page.add(bar) # scatter3D import random data = [ [random.randint(0, 100), random.randint(0, 100), random.randint(0, 100)] for _ in range(80) ] scatter3d = Scatter3D("3D 散点图示例", width=1200, height=600) scatter3d.add("", data, is_visualmap=True, visual_range_color=RANGE_COLOR) page.add(scatter3d) # guangdong value = [20, 190, 253, 77, 65] attr = ['汕头市', '汕尾市', '揭阳市', '阳江市', '肇庆市'] map = Map("广东地图示例", width=1200, height=600) map.add("", attr, value, maptype='广东', is_visualmap=True, visual_text_color='#000') page.add(map) return page
def test_numpy_array(): v1 = np.array([5, 20, 36, 10, 75, 90]) bar = Bar(TITLE) bar.add("商家A", CLOTHES, v1, is_stack=True) html = bar.render_embed() json_encoded_title = json.dumps(TITLE) assert json_encoded_title in html
def test_custom_template_for_chart(): data = [{ 'name': '衬衫', 'value': 5 }, { 'name': '羊毛衫', 'value': 20 }, { 'name': '雪纺衫', 'value': 36 }] configure(echarts_template_dir='.') online() data1 = {'衬衫': '34', '羊毛衫': 45, '雪纺衫': 40} names, values = Bar.cast(data) names1, values1 = Bar.cast(data1) bar = Bar("柱状图数据堆叠示例") bar.add("商家A", names, values, is_stack=True) bar.add("商家B", names1, values1, is_stack=True) bar.render(path='new_version_bar.html') with codecs.open('new_version_bar.html', 'r', 'utf-8') as f: actual_content = f.read() assert "</html>" in actual_content
def test_grid_properties(): v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] bar = Bar("柱状图示例", height=720) bar.add("商家A", CLOTHES, v1, is_stack=True) bar.add("商家B", CLOTHES, v2, is_stack=True) line = Line("折线图示例", title_top="50%") line.add( "最高气温", WEEK, [11, 11, 15, 13, 12, 13, 10], mark_point=["max", "min"], mark_line=["average"], ) line.add( "最低气温", WEEK, [1, -2, 2, 5, 3, 2, 0], mark_point=["max", "min"], mark_line=["average"], legend_top="50%", ) grid = Grid(width=1024, height=768) grid.add(bar, grid_bottom="60%") grid.add(line, grid_top="60%") eq_(grid.width, 1024) eq_(grid.height, 768) assert ( ("echarts" in bar.js_dependencies) or ("echarts.min" in bar.js_dependencies) )
def create_a_bar(title): v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] bar = Bar(title) bar.add("商家A", CLOTHES, v1, is_stack=True) bar.add("商家B", CLOTHES, v2, is_stack=True) return bar
def test_grid_four_direction(): v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] bar = Bar("柱状图示例", height=720, width=1200, title_pos="65%") bar.add("商家A", CLOTHES, v1, is_stack=True) bar.add("商家B", CLOTHES, v2, is_stack=True, legend_pos="80%") line = Line("折线图示例") line.add("最高气温", WEEK, [11, 11, 15, 13, 12, 13, 10], mark_point=["max", "min"], mark_line=["average"]) line.add("最低气温", WEEK, [1, -2, 2, 5, 3, 2, 0], mark_point=["max", "min"], mark_line=["average"], legend_pos="20%") v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] scatter = Scatter("散点图示例", title_top="50%", title_pos="65%") scatter.add("scatter", v1, v2, legend_top="50%", legend_pos="80%") es = EffectScatter("动态散点图示例", title_top="50%") es.add("es", [11, 11, 15, 13, 12, 13, 10], [1, -2, 2, 5, 3, 2, 0], effect_scale=6, legend_top="50%", legend_pos="20%") grid = Grid() grid.add(bar, grid_bottom="60%", grid_left="60%") grid.add(line, grid_bottom="60%", grid_right="60%") grid.add(scatter, grid_top="60%", grid_left="60%") grid.add(es, grid_top="60%", grid_right="60%") grid.render()
def test_bar_rotate_label(): days = ["{}天".format(i) for i in range(20)] days_v1 = [random.randint(1, 20) for _ in range(20)] bar = Bar("坐标轴标签旋转示例") bar.add("", days, days_v1, xaxis_interval=0, xaxis_rotate=30, yaxis_rotate=30) assert "stack_" not in bar._repr_html_()
def test_bar_datazoom_undefined(): days = ["{}天".format(i) for i in range(30)] days_v1 = [random.randint(1, 30) for _ in range(30)] bar = Bar("Bar - datazoom 默认 示例") bar.add("", days, days_v1, is_label_show=True, is_datazoom_show=True) html_content = bar._repr_html_() assert "dataZoom" in html_content assert ': "slider"' in html_content assert ': "inside"' not in html_content
def test_bar_datazoom_inside(): days = ["{}天".format(i) for i in range(30)] days_v1 = [random.randint(1, 30) for _ in range(30)] bar = Bar("Bar - datazoom - inside 示例") bar.add("", days, days_v1, is_datazoom_show=True, datazoom_type='inside', datazoom_range=[10, 25]) html_content = bar._repr_html_() assert "dataZoom" in html_content assert ': "inside"' in html_content assert ': "slider"' not in html_content
def create_demo_bar(chart_id_demo=None): attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"] v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] bar = Bar("柱状图数据堆叠示例") bar.add("商家A", attr, v1, is_stack=True) bar.add("商家B", attr, v2, is_stack=True) if chart_id_demo: bar._chart_id = chart_id_demo return bar
def test_bar_waterfall(): months = ["{}月".format(i) for i in range(1, 8)] months_v1 = [0, 100, 200, 300, 400, 220, 250] months_v2 = [1000, 800, 600, 500, 450, 400, 300] bar = Bar("瀑布图示例") bar.add("", months, months_v1, label_color=['rgba(0,0,0,0)'], is_stack=True) bar.add("月份", months, months_v2, is_label_show=True, is_stack=True, label_pos='inside') bar.show_config() bar.render()
def test_numpy_array(): import numpy as np title = "柱状图数据堆叠示例" attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"] v1 = np.array([5, 20, 36, 10, 75, 90]) bar = Bar(title) bar.add("商家A", attr, v1, is_stack=True) html = bar.render_embed() json_encoded_title = json.dumps(title) assert json_encoded_title in html
def draw_data_echart(select_results): list_name = [] list_count = [] for select_list in select_results: list_name.append(select_list[0]) list_count.append(int(select_list[2])) #print ("select name: %s, select count: %d" % (select_list[0], int(select_list[2]))) bar = Bar("read weekly", "download count") bar.use_theme('light') bar.add("book download count", list_name, list_count, is_more_utils = True, is_label_show = True, is_datazoom_show = True) bar.render("downloadcount.html")
def test_chart_properties(): v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] bar = Bar("柱状图-数据堆叠示例", width=900, height=500) bar.add("商家A", CLOTHES, v1, is_stack=True) bar.add("商家B", CLOTHES, v2, is_stack=True) eq_(len(bar.chart_id), UUID_HEX_LENGTH) eq_(bar.width, 900) eq_(bar.height, 500) assert ('echarts' in bar.js_dependencies) or \ ('echarts.min' in bar.js_dependencies)
def test_overlap_bar_line(): attr = ["A", "B", "C", "D", "E", "F"] v1 = [10, 20, 30, 40, 50, 60] v2 = [38, 28, 58, 48, 78, 68] bar = Bar("Line-Bar 示例") bar.add("bar", attr, v1) line = Line() line.add("line", attr, v2) overlap = Overlap() overlap.add(bar) overlap.add(line) overlap.render()
def generic_formatter_t_est(**keywords): attr = ["Jan", "Feb"] v1 = [2.0, 4.9] bar = Bar("Bar chart", "precipitation and evaporation one year") bar.add( "precipitation", attr, v1, mark_line=["average"], mark_point=["max", "min"], **keywords ) bar.render()
def get_bar(item_name,item_name_list,item_num_list): subtitle = "微信公众号:大数据前沿" bar = Bar(item_name,page_title = item_name,title_text_size=30,title_pos='center',\ subtitle = subtitle,subtitle_text_size = 25) bar.add("", item_name_list, item_num_list,title_pos='center', xaxis_interval=0,xaxis_rotate=27,\ xaxis_label_textsize = 20,yaxis_label_textsize = 20,yaxis_name_pos='end',yaxis_pos = "%50") bar.show_config() grid = Grid(width=1300,height= 800) grid.add(bar,grid_top = "13%",grid_bottom = "23%",grid_left = "15%",grid_right = "15%") out_file_name = './analyse/'+item_name+'.html' grid.render(out_file_name)
def test_overlap_bar_line(): attr = ['A', 'B', 'C', 'D', 'E', 'F'] v1 = [10, 20, 30, 40, 50, 60] v2 = [38, 28, 58, 48, 78, 68] bar = Bar("Line-Bar 示例") bar.add("bar", attr, v1) line = Line() line.add("line", attr, v2) overlap = Overlap() overlap.add(bar) overlap.add(line) overlap.render()
def test_timeline_bar_line(): attr = ["{}月".format(i) for i in range(1, 7)] bar = Bar("1 月份数据", "数据纯属虚构") bar.add("bar", attr, [randint(10, 50) for _ in range(6)]) line = Line() line.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_0 = Overlap() overlap_0.add(bar) overlap_0.add(line) bar_1 = Bar("2 月份数据", "数据纯属虚构") bar_1.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_1 = Line() line_1.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_1 = Overlap() overlap_1.add(bar_1) overlap_1.add(line_1) bar_2 = Bar("3 月份数据", "数据纯属虚构") bar_2.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_2 = Line() line_2.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_2 = Overlap() overlap_2.add(bar_2) overlap_2.add(line_2) bar_3 = Bar("4 月份数据", "数据纯属虚构") bar_3.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_3 = Line() line_3.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_3 = Overlap() overlap_3.add(bar_3) overlap_3.add(line_3) bar_4 = Bar("5 月份数据", "数据纯属虚构") bar_4.add("bar", attr, [randint(10, 50) for _ in range(6)]) line_4 = Line() line_4.add("line", attr, [randint(50, 80) for _ in range(6)]) overlap_4 = Overlap() overlap_4.add(bar_4) overlap_4.add(line_4) timeline = Timeline(timeline_bottom=0) timeline.add(overlap_0, "1 月") timeline.add(overlap_1, "2 月") timeline.add(overlap_2, "3 月") timeline.add(overlap_3, "4 月") timeline.add(overlap_4, "5 月") timeline.render()
def test_embed_option(): # bar_0 title = "柱状图数据堆叠示例" attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"] v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] bar = Bar(title) bar.add("商家A", attr, v1, is_stack=True) bar.add("商家B", attr, v2, is_stack=True) html = bar.render_embed() json_encoded_title = json.dumps(title) assert json_encoded_title in html assert "<html>" not in html assert "<body>" not in html
def test_pandas_dataframe(): title = "bar chart" index = pd.date_range("3/8/2017", periods=6, freq="M") df1 = pd.DataFrame(np.random.randn(6), index=index) df2 = pd.DataFrame(np.random.randn(6), index=index) dtvalue1 = [i[0] for i in df1.values] dtvalue2 = [i[0] for i in df2.values] _index = [i for i in df1.index.format()] bar = Bar(title, "Profit and loss situation") bar.add("profit", _index, dtvalue1) bar.add("loss", _index, dtvalue2) html = bar.render_embed() assert title in html
def test_bar_datazoom_both(): days = ["{}天".format(i) for i in range(30)] days_v1 = [random.randint(1, 30) for _ in range(30)] bar = Bar("Bar - datazoom - both 示例") bar.add( "", days, days_v1, is_datazoom_show=True, datazoom_type="both", datazoom_range=[10, 25], is_toolbox_show=False, ) html_content = bar._repr_html_() assert "dataZoom" in html_content assert ': "inside"' in html_content assert ': "slider"' in html_content
def test_overlap_two_yaxis(): attr = ["{}月".format(i) for i in range(1, 13)] v1 = [2.0, 4.9, 7.0, 23.2, 25.6, 76.7, 135.6, 162.2, 32.6, 20.0, 6.4, 3.3] v2 = [2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3] v3 = [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2] bar = Bar(width=1200, height=600) bar.add("蒸发量", attr, v1) bar.add("降水量", attr, v2, yaxis_formatter=" ml", yaxis_max=250) line = Line() line.add("平均温度", attr, v3, yaxis_formatter=" °C") overlap = Overlap() overlap.add(bar) overlap.add(line, yaxis_index=1, is_add_yaxis=True) overlap.render()
def test_grid_heatmap_bar(): data = [[i, j, random.randint(0, 50)] for i in range(24) for j in range(7)] heatmap = HeatMap("热力图示例", height=700) heatmap.add("热力图直角坐标系", X_TIME, Y_WEEK, data, is_visualmap=True, visual_top="45%", visual_text_color="#000", visual_orient='horizontal') v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] bar = Bar("柱状图示例", title_top="52%") bar.add("商家A", CLOTHES, v1, is_stack=True) bar.add("商家B", CLOTHES, v2, is_stack=True, legend_top="50%") grid = Grid() grid.add(heatmap, grid_bottom="60%") grid.add(bar, grid_top="60%") grid.render()
def draw_citys_pic(csv_file): page = Page(csv_file+":评论城市分析") info = count_city(csv_file) geo = Geo("","Ctipsy原创",title_pos="center", width=1200,height=600, background_color='#404a59', title_color="#fff") while True: # 二次筛选,和pyecharts支持的城市库进行匹配,如果报错则删除该城市对应的统计 try: attr, val = geo.cast(info) geo.add("", attr, val, visual_range=[0, 300], visual_text_color="#fff", is_geo_effect_show=False, is_piecewise=True, visual_split_number=6, symbol_size=15, is_visualmap=True) except ValueError as e: e = str(e) e = e.split("No coordinate is specified for ")[1] # 获取不支持的城市名称 info.pop(e) else: break info = sorted(info.items(), key=lambda x: x[1], reverse=False) # list排序 # print(info) info = dict(info) #list转dict # print(info) attr, val = [], [] for key in info: attr.append(key) val.append(info[key]) geo1 = Geo("", "评论城市分布", title_pos="center", width=1200, height=600, background_color='#404a59', title_color="#fff") geo1.add("", attr, val, visual_range=[0, 300], visual_text_color="#fff", is_geo_effect_show=False, is_piecewise=True, visual_split_number=10, symbol_size=15, is_visualmap=True, is_more_utils=True) #geo1.render(csv_file + "_城市dotmap.html") page.add_chart(geo1) geo2 = Geo("", "评论来源热力图",title_pos="center", width=1200,height=600, background_color='#404a59', title_color="#fff",) geo2.add("", attr, val, type="heatmap", is_visualmap=True, visual_range=[0, 50],visual_text_color='#fff', is_more_utils=True) #geo2.render(csv_file+"_城市heatmap.html") # 取CSV文件名的前8位数 page.add_chart(geo2) bar = Bar("", "评论来源排行", title_pos="center", width=1200, height=600 ) bar.add("", attr, val, is_visualmap=True, visual_range=[0, 100], visual_text_color='#fff',mark_point=["average"],mark_line=["average"], is_more_utils=True, is_label_show=True, is_datazoom_show=True, xaxis_rotate=45) #bar.render(csv_file+"_城市评论bar.html") # 取CSV文件名的前8位数 page.add_chart(bar) pie = Pie("", "评论来源饼图", title_pos="right", width=1200, height=600) pie.add("", attr, val, radius=[20, 50], label_text_color=None, is_label_show=True, legend_orient='vertical', is_more_utils=True, legend_pos='left') #pie.render(csv_file + "_城市评论Pie.html") # 取CSV文件名的前8位数 page.add_chart(pie) page.render(csv_file + "_城市评论分析汇总.html")
def region_distribution(): # 使用一个字典统计好友地区分布数量 province_dict = { '北京': 0, '上海': 0, '天津': 0, '重庆': 0, '河北': 0, '山西': 0, '吉林': 0, '辽宁': 0, '黑龙江': 0, '陕西': 0, '甘肃': 0, '青海': 0, '山东': 0, '福建': 0, '浙江': 0, '台湾': 0, '河南': 0, '湖北': 0, '湖南': 0, '江西': 0, '江苏': 0, '安徽': 0, '广东': 0, '海南': 0, '四川': 0, '贵州': 0, '云南': 0, '内蒙古': 0, '新疆': 0, '宁夏': 0, '广西': 0, '西藏': 0, '香港': 0, '澳门': 0 } # 遍历 for user in friends: # 判断省份是否存在,有可能是外国的,这种情况不考虑 if (user.province in province_dict): key = user.province province_dict[key] += 1 province = list(province_dict.keys()) values = list(province_dict.values()) # maptype='china' 只显示全国直辖市和省级,数据只能是省名和直辖市的名称 map = Map("微信好友地区分布") map.add("", province, values, visual_range=[0, 50], maptype='china', is_visualmap=True, visual_text_color='#000') map.render(path="data/好友地区分布.html") # 对好友数最多的省份进行一进步分析 max_count_province = '' for key, value in province_dict.items(): if (value == max(province_dict.values())): max_count_province = key break # 使用一个字典统计好友地区分布数量 city_dict = {} # 遍历 for user in friends: if (user.province == max_count_province): # 更新键值对 if (user.city in city_dict.keys()): city_dict[user.city] += 1 else: city_dict[user.city] = 1 bar = Bar(max_count_province + '中,好友地区分布') bar.add(name='地区分布', x_axis=[x for x in city_dict.keys()], y_axis=[x for x in city_dict.values()]) bar.render('data/某省好友地区分布.html')
df_huanjing['环境']=df_huanjing['环境'].map(lambda x:round(x,2)) df_fuwu=df.drop(df[df['服务']==0].index,inplace=False) df_fuwu=df_fuwu.groupby(by='城市').agg({'服务':'mean'}).reset_index() df_fuwu=df_fuwu.sort_values(by='服务',ascending=False)[0:20] df_fuwu['服务']=df_fuwu['服务'].map(lambda x:round(x,2)) # 柱状图 bar1=Bar('小龙虾人气城市',title_top="10px",title_pos="5%") bar2=Bar('人均消费排名',title_top="180px",title_pos="5%") bar3=Bar('口味评分排名',title_top="350px",title_pos="5%") bar4=Bar('环境评分排名',title_top="520px",title_pos="5%") bar5=Bar('服务评分排名',title_top="690px",title_pos="5%") # is_splitline_show 水平标线 xaxis_rotate 未知 legend_top 图例离页面顶部距离 bar1.add('点评',df_dianping['城市'],df_dianping['点评'],is_splitline_show=True,xaxis_rotate=30,legend_top="10px",legend_pos="50%") bar2.add('人均消费',df_renjun['城市'],df_renjun['人均'],is_splitline_show=True,xaxis_rotate=30,legend_top="180px",legend_pos="50%") bar3.add('评分',df_kouwei['城市'],df_kouwei['口味'],is_splitline_show=True,xaxis_rotate=30,legend_top="350px",legend_pos="50%") bar4.add('评分',df_huanjing['城市'],df_huanjing['环境'],is_splitline_show=True,xaxis_rotate=30,legend_top="520px",legend_pos="50%") bar5.add('评分',df_fuwu['城市'],df_fuwu['服务'],is_splitline_show=True,xaxis_rotate=30,legend_top="690px",legend_pos="50%") grid = Grid(height=1200,width=1280) # grid_bottom 图表底部离页面底部距离 grid_top 图表顶部离页面顶部距离 '''100%-(grid_bottom:80 + grid_top 5)=15%即为柱状图高的占比, 即4个图占60%空间,并留一些白''' '''先填出第一个图(80,5)与最后一个图(5,80)的位置, 然后用(80-5)/(4-1)=25为增量间距''' # grid.add(bar1,grid_bottom="80%",grid_top="6%" ,grid_left="5%",grid_right="55%") grid.add(bar1,grid_top="50px",grid_bottom="1050px") grid.add(bar2,grid_top="220px",grid_bottom="880px") grid.add(bar3,grid_top="390px",grid_bottom="710px") grid.add(bar4,grid_top="560px",grid_bottom="540px") grid.add(bar5,grid_top="730px",grid_bottom="370px")
from pyecharts import Bar def RE(p): length = len(p) - 1 for i in range(int(length / 2 + 1)): p[i], p[length - i] = p[length - i], p[i] return list(p) # 1:is_stack 实现数据堆叠 # Note: 全局配置项要在最后一个 add() 上设置,否侧设置会被冲刷掉。 attr = [x for x in range(1998, 2018)] v1 = [ 139008, 138271, 137462, 136782, 136072, 135404, 134735, 134091, 133450, 132802, 132129, 131448, 130756, 129988, 129227, 128453, 127627, 126743, 125786, 124761 ] v2 = [ 824828.4, 740598.7, 686449.6, 644791.1, 590422.4, 539116.5, 484753.2, 411265.2, 348498.5, 321500.5, 270844, 219028.5, 185998.9, 161415.4, 136576.3, 120480.4, 109276.2, 99066.1, 89366.5, 83817.6 ] v3 = [float(v2[i]) / float(v1[i]) for i in range(len(v1))] # 2:使用标记点和标记线 bar = Bar("生产总值") bar.add("平均个人", attr, RE(v3), mark_point=["average"], is_stack=False) bar.add("总体", attr, RE(v2), mark_line=["min", "max"], is_stack=False) bar.render("GDP.html")
def index5(request): if request.method == 'GET': pclass_list = models.Professionalclass.objects.all() course_list = models.Course.objects.all() return render(request, 'index5.html', locals()) else: from pyecharts import Bar courses = request.POST.getlist('courses') #['1','2','4'] pclass = request.POST.get('pclass') ll = [] createVar = locals() dic = {} list2 = [] for course in courses: dic['v' + course] = course course_name = models.Course.objects.filter(id=course).first() tup1 = ['v' + course, course_name.name] list2.append(tup1) # print(list2) l2 = [] for key, value in dic.items(): # key=value l2.append(key) dic1 = {} for course in courses: for i in l2: if 'v' + course == i: grades = models.Grade.objects.filter( course=course, student__pclass=pclass).all().values_list('grade') dic1[i] = grades # print(dic1) dic3 = {} for i in l2: dic3[i] = [] for j in dic1[i]: j = int(j[0]) dic3[i].append(j) students = models.Grade.objects.filter(student__pclass=pclass).all( ).values_list('student__name').distinct() attr = [] for student in students: attr.append(student[0]) # print(attr) bar = Bar("柱状图数据堆叠示例", width=1600) # print(dic3) for i in l2: for j in list2: if j[0] == i: dic = dic3[i] if len(dic3[i]) != len(attr): l = [] for k in range(len(attr)): l.append(0) for i in dic: print(i) names = models.Grade.objects.filter( grade=i, student__pclass=pclass, course__name=j[1]).all().values_list( 'student__name') for name in names: print(name) index = attr.index(name[0]) print(index) l[index] = i print(l) dic = l # print(attr) # print(dic) print('--------start') print(len(attr)) #21 print(len(dic)) #21 print('--------start') bar.add(j[1], attr, dic, mark_line=["average"]) # v1 = l2 # ['王芳泽', '王芳泽', '王芳泽', '李晓瑶', '李晓瑶', '李晓瑶', '张凡儿', '张凡儿', '张凡儿', '刘英豪', '刘英豪', '刘英豪', '杨思萱', '杨思萱', '杨思萱', '黄建元', # '黄建元', '黄建元', '周翔飞', '周翔飞', '周翔飞', '王飞燕', '王飞燕', '王飞燕', '吴明杰', '吴明杰', '吴明杰', '林强', '林强', '林强', '刘勇捷', '刘勇捷', '刘勇捷', # '黄阳', '黄阳', '黄阳', '陈静逸', '陈静逸', '陈静逸', '张安怡', '张安怡', '张安怡', '刘俊名', '刘俊名', '刘俊名', '王瑶', '王瑶', '王瑶', '李宏儒', '李宏儒', # '李宏儒', '朱乐欣', '朱乐欣', '朱乐欣', '李清照', '李清照', '李清照', '马逸龙', '马逸龙', '马逸龙', '林美美', '林美美', '林美美'] # [87, 85, 85, 98, 72, 87, 87, 79, 88, 92, 90, 75, 85, 88, 89, 83, 86, 80, 81, 95, 74, 92, 90, 93, 91, 88, 80, 94, 72, # 70, 88, 89, 71, 93, 80, 90, 93, 83, 92, 96, 94, 93, 72, 70, 74, 99, 97, 98, 90, 92, 80, 88, 78, 60, 78, 79, 89, 87, # 81, 76, 82, 70, 90] bar.render('templates/imagelist/contrast_grade.html') return render(request, 'imagelist/contrast_grade.html')
bank = data.sheets()[1] print(table.col_values(0)) print(bank.col_values(0)) # X轴 CLOTHES = table.col_values(0) # 数据 clothes_pv = table.col_values(1) clothes_uv = table.col_values(2) clothes_ip = table.col_values(3) # print(clothes_pv, clothes_uv, clothes_ip) # bar = Bar("account_ekeguan_com", height=720) bar = Bar("account_ekeguan_com", height=350) bar.add("PV", CLOTHES, clothes_pv) bar.add("UV", CLOTHES, clothes_uv) bar.add("IP", CLOTHES, clothes_ip, is_stack=False, is_datazoom_show=True) # X轴 CLOTHES = bank.col_values(0) # 数据 clothes_pv = bank.col_values(1) clothes_uv = bank.col_values(2) clothes_ip = bank.col_values(3) # print(clothes_pv, clothes_uv, clothes_ip) line = Bar("www_ekeguan_com", title_top='1%') line.add("PV", CLOTHES, clothes_pv) line.add("UV", CLOTHES, clothes_uv) line.add("IP", CLOTHES, clothes_ip, is_stack=False, is_datazoom_show=True)
def ple_edcation_of_eachcity(htmlfile): lasa = [0.46, 5.56, 7.20, 9.47, 21.10, 36.62, 19.59] # 拉萨市 cangdu = [0.04, 0.94, 1.75, 2.36, 10.28, 39.92, 44.7] #昌都市 sanlan = [0.05, 2.41, 3.39, 5.54, 16.08, 50.99, 21.55] #山南市 rkz = [0.03, 1.68, 2.41, 3.79, 14.87, 43.88, 33.35] # 日喀则市 naqu = [0.03, 1.16, 2.29, 2.78, 8.38, 35.25, 50.11] #那曲地区 ali = [0.05, 2.73, 4.64, 5.22, 10.89, 32.54, 43.93] #阿里地区 linz = [0.14, 2.52, 3.46, 4.84, 14.26, 40.60, 34.19] #林芝地区 attr = ['研究生', '本科', '专科', '高中', '初中', '小学', '未上过学'] bar = Bar("2010年西藏各城市学历", width=1000, height=400) bar.add("拉萨市", attr, lasa) bar.add("昌都市", attr, cangdu) bar.add("山南市", attr, sanlan) bar.add("日喀则市", attr, rkz) bar.add("那曲地区", attr, naqu) bar.add("阿里地区", attr, ali) bar.add("林芝地区", attr, linz) bar.show_config() bar.render(htmlfile)
a['sort_num_score'] = a['score'].rank(ascending=0, method='dense') a['value'] = a.apply(lambda row: my_difference(row['sort_num_money'], row[ 'sort_num_score'], len(a.index)), axis=1) df = a.sort_values(by="value", ascending=True)[0:9] v1 = ["{}".format('%.2f' % abs(i * 100)) for i in df['value']] attr = np.array(df['name']) attr = ["{}".format(i.replace(':无限战争', '')) for i in attr] bar = Bar("2018年叫座不叫好电影TOP10", title_pos='center', title_top='18', width=800, height=400) bar.add("", attr, v1, is_convert=True, xaxis_min=0, xaxis_max=4, yaxis_label_textsize=12, is_yaxis_boundarygap=True, yaxis_interval=0, is_label_show=True, is_legend_show=False, label_pos='right', is_yaxis_inverse=True, is_splitline_show=False) bar.render("2018年叫座不叫好电影TOP100.html")
if i[tuple(i.keys())[0]] <700:#如果价格小于700,则添加进一个数组 item_shenzhen = ["深圳",tuple(i.keys())[0]] data_shenzhen.append(item_shenzhen) style_geo = style.add(#地图的参数设置,包括图标,位置 is_label_show=True, line_curve=0.2, line_opacity=0.6, legend_text_color="#eee", legend_pos="right", geo_effect_symbol="plane",#图标改成了飞机 geo_effect_symbolsize=15, label_color=['#a6c84c', '#ffa022', '#46bee9'], label_pos="right", label_formatter="{b}", label_text_color="#eee", ) geolines = GeoLines("GeoLines 示例", **style.init_style) geolines.add("从深圳出发", data_shenzhen, **style_geo) geolines.render(path='road.html') from pyecharts import Bar#引入包 echart_city=[]#城市 echart_price=[]#价格 for p in data_price:#遍历数据,将城市和价格分开 if p[tuple(p.keys())[0]]<700: echart_city.append(tuple(p.keys())[0]) echart_price.append(p[tuple(p.keys())[0]]) bar = Bar("航班价格", "从深圳出发")#标题 bar.add("城市", echart_city,echart_price)#将城市、价格数据导入 bar.render(path='bar.html')#生成
#上面是mongodb聚合统计的语句 #$group:按照给定表达式组合结果,这里的_id字段表示你要基于哪个字段来进行分组,这里的$city就表示要基于city字段来进行分组 #下面的count字段的值$sum: 1表示的是获取--满足city字段相同的这一组的数量--乘以后面给定的值(本例为1,那么就是同组的数量)。 #$sort:按照给定的字段排序结果,即按计算好的count排序,-1为降序来排列 for i in res: print(i) #{'_id': '成都', 'count': 2074} all.append((i['_id'].strip(), i['count'])) attr = [i[0] for i in all[:30]] #取前三十城市的名字 v1 = [i[1] for i in all[:30]] #取前三十城市的值 print(attr) bar = Bar('新房分布柱状图') #柱状图 bar.add('各城市新楼盘数', attr, v1, is_label_show=True, is_datazoom_show=True, xaxis_rotate=65, label_color=[ '#87CEEB', ]) #attr 下面的城市名 #v1 数值 #is_label_show -> bool 是否正常显示标签,默认不显示。即各柱上的数字 #is_datazoom_show -> bool 是否使用区域缩放组件,默认为 False #xaxis_rotate -> int x 轴刻度标签旋转的角度,默认为 0,即不旋转。旋转的角度从 -90 度到 90 度。 #label_color 柱的颜色 bar.render('bar.html')
# -*- coding:utf-8 -*- # @Author:sunaihua import pyecharts from pyecharts import Bar bar = Bar("我的第一个图表", "这里是副标题") bar.use_theme('dark') #暗色背景色 bar.add( "服装", #注解==label ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], #横坐标 [5, 20, 36, 10, 75, 90]) #纵坐标 bar.render('./picture1.html') #文件存储路径(默认保存当前文件路径)
line_curve=0.1, #轨迹线的弯曲度,0-1 line_opacity=0.6, #轨迹线的透明度,0-1 geo_effect_symbol='plane', #特效的图形,有circle,plane,pin等等 geo_effect_symbolsize=8, #特效图形的大小 geo_effect_color='#7FFFD4', #特效的颜色 geo_effect_traillength=0.1, #特效图形的拖尾效果,0-1 label_color=colors[i], #轨迹线的颜色,标签点的颜色, border_color='#97FFFF', #边界的颜色 geo_normal_color='#36648B', #地图的颜色 legend_pos='left', label_formatter='{b}') geolines.add( name=rdc_name[i], data=flow, maptype='china', #地图的类型,可以是省的地方,如'广东',也可以是地市,如'东莞'等等 geo_cities_coords=City_cords, **style_geolines) #发布,得到图形的html文件 geolines.render("py十仓仓网覆盖.html") ##堆叠柱状图 x = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"] y1 = [5, 20, 36, 10, 75, 90] y2 = [10, 25, 8, 60, 20, 80] bar = Bar("柱状图数据堆叠示例") title1 = '商家A' title2 = '商家B' bar.add(title1, x, y1, is_stack=True) bar.add(title2, x, y2, is_stack=True) bar.render('柱状图数据堆叠.html')
import pandas as pd from pyecharts import Bar df = pd.read_csv('Best_Actor_SR.csv', header=None, names=['year', 'win', 'nomination'], encoding='gbk') win_message = df.groupby(['win']) win_com = win_message['win'].agg(['count']) win_com.reset_index(inplace=True) win_com_last = win_com.sort_index() win_com = win_com.sort_values('count', ascending=False)[0:15] attr = win_com['win'] v1 = win_com['count'] bar = Bar("奥斯卡最佳男配角-获奖统计", title_pos='center', title_top='18', width=800, height=400) bar.add("", attr, v1, is_stack=True, is_label_show=True, xaxis_rotate=30, yaxis_force_interval=1, yaxis_max=4) bar.render("奥斯卡最佳男配角-获奖统计.html")
def bar_echart(request, *args, **kwargs): template = loader.get_template( './node_modules/gentelella/production/display_metric_detail.html') snap = request.GET.get('snapdate') #snap_date = datetime.strptime(snap, '%y/%m/%d').strftime('%Y-%m-%d') if snap: load_profile_per_hour = list( models.loadmetric_hour.objects.values( "time", "redo_second", "logical_second", "physical_second", "execs_second", "trans_second").filter(snap_date=snap).all()) space_usage = list( models.spaceusage.objects.values( "tablespace_name", "percent").filter(collect_time=snap).all()) print(space_usage) # load_profile_obj = apps.get_model('ora_dual', 'loadmetric_hour') # load_profile_field = load_profile_obj._meta.fields # title = [] # for ind in range(len(load_profile_field)): # title.append(load_profile_field[ind].name) attr = [] for key, value in load_profile_per_hour[0].items(): attr.append(key) val_usage = [] val_name = [] for idx in range(len(space_usage)): val_name.append(space_usage[idx]['tablespace_name']) val_usage.append(space_usage[idx]['percent']) usage_pie = Pie("饼图-空间使用率", title_pos='center') usage_pie.add( "", val_name, val_usage, radius=[40, 75], label_text_color=None, is_label_show=True, legend_orient="vertical", legend_pos="left", ) # pie.render() timeline = Timeline(is_auto_play=True, timeline_bottom=0) for idx in range(len(load_profile_per_hour)): val = [] for key, value in load_profile_per_hour[idx].items(): val.append(value) bar = Bar("数据库指标", val[0]) bar.add("值/秒", attr[1:], val[1:]) timeline.add(bar, val[0]) context = dict( snap_date=snap, title=attr, usage_pie=usage_pie.render_embed(), space_usage=space_usage, metric_data=load_profile_per_hour, myechart=timeline.render_embed(), # host=DEFAULT_HOST,#这句改为下面这句 host=REMOTE_HOST, # <-----修改为这个 script_list=timeline.get_js_dependencies()) return HttpResponse(template.render(context, request))
def chart(self): bar = Bar("ebooking") bar.add("60客户", self.percent, self.sortList, is_stack=True) bar.render() make_a_snapshot('render.html', './pic/%s.png' % self.name)
from pyecharts import Bar bar=Bar('图表标题','图标副标题') bar.use_theme('dark') kind=["衬衫","羊毛衫","雪纺衫","裤子","高跟鞋","袜子"] bar.add('服装',kind,[5,20,36,10,75,90],is_more_utils=True) bar.render()
item = { 'nickname': hotcommment['user']['nickname'], 'content': hotcommment['content'], 'likedCount': hotcommment['likedCount'] } hotcomments.append(item) # 获取评论用户名,内容,以及对应的获赞数 content_list = [content['content'] for content in hotcomments] nickname = [content['nickname'] for content in hotcomments] liked_count = [content['likedCount'] for content in hotcomments] bar = Bar("热评中点赞数示例图") bar.add("点赞数", nickname, liked_count, is_stack=True, mark_line=["min", "max"], mark_point=["average"]) bar.render() from wordcloud import WordCloud import matplotlib.pyplot as plt content_text = " ".join(content_list) wordcloud = WordCloud(font_path=r"D:\simhei.ttf", max_words=200).generate(content_text) plt.figure() plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.show()
from pyecharts import Bar from pyecharts_snapshot.main import make_a_snapshot bar = Bar("我的第一个图表") bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90]) bar.add("鞋子", ["衬", "羊衫", "纺衫", "裤", "高鞋", "袜"], [5, 20, 36, 10, 75, 90], is_more_utils=True) bar.render('Source/2.html')
结合不同类型图表叠加画在同张图上 Overlap 类的使用: 1、引入 Overlap 类,from pyecharts import Overlap 2、实例化 Overlap 类,overlap = Overlap() ,可指定 page_title, width, height, jhost 参数。 3、使用 add() 向 overlap 中添加图 4、使用 render() 渲染生成 .html 文件 Overlap.add() 方法签名 add(chart, 图表示例 xaxis_index=0, x 坐标轴索引,默认为 0 yaxis_index=0, y 坐标轴索引,默认为 0 is_add_xaxis=False, 是否新增一个 x 坐标轴,默认为 False is_add_yaxis=False) 是否新增一个 y 坐标轴,默认为 False ''' # Line + Bar from pyecharts import Overlap,Line,Bar attr=['A', 'B', 'C', 'D', 'E', 'F'] v1=[10, 20, 30, 40, 50, 60] v2=[38, 28, 58, 48, 78, 68] bar=Bar('Line-Bar示例') bar.add('bar',attr,v1) line=Line() line.add('line',attr,v2) overlap=Overlap() overlap.add(line) overlap.add(bar) overlap.render()
from mymodule import stats_word import requests from pyquery import PyQuery import matplotlib.pyplot as plt import numpy as np from pyecharts import Bar def get_article(): url = 'https://mp.weixin.qq.com/s/pLmuGoc4bZrMNl7MSoWgiA' r = requests.get(url) document = PyQuery(r.text) article_str = document('#js_content').text() result = stats_word.stats_text_cn(article_str, 10) return result paixu = get_article() paixu_list = [] for paixu_tuple in paixu: for paixu_str in paixu_tuple: paixu_list.append(paixu_str) name = paixu_list[::2] #取出所有名字 number = paixu_list[1::2] #取出所有对应的词频数 bar = Bar('词频输出') bar.add('词频', name, number) bar.show_config() bar.render()
# -*- coding: utf-8 -*- """ @author:XuMing([email protected]) @description: """ from __future__ import unicode_literals from pyecharts import Bar from pyecharts.conf import PyEchartsConfig from pyecharts.engine import EchartsEnvironment from pyecharts.utils import write_utf8_html_file attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"] v1 = [5, 20, 36, 10, 75, 90] v2 = [10, 25, 8, 60, 20, 80] bar = Bar("柱状图数据堆叠示例") bar.add("商家A", attr, v1, is_stack=True) bar.add("商家B", attr, v2, is_stack=True) config = PyEchartsConfig(echarts_template_dir='./', jshost='https://cdn.bootcss.com/echarts/3.6.2') env = EchartsEnvironment(pyecharts_config=config) tpl = env.get_template('tpl.html') html = tpl.render(bar=bar) write_utf8_html_file('my_tpl_demo2.html', html)
'nickname': hotcomment['user']['nickname'], 'content': hotcomment['content'], 'likedCount': hotcomment['likedCount'] } hotcomments.append(item) #获取评论用户名,内容,以及对应的获赞数 content_list = [content['content'] for content in hotcomments] nickname = [content['nickname'] for content in hotcomments] liked_count = [content['likedCount'] for content in hotcomments] #点赞数 from pyecharts import Bar #pyecharts:图表包 bar = Bar('热门中点赞数示例图') bar.add('点赞数', nickname, liked_count, is_stack=True, mark_line=['min', 'max'], mark_point=['average']) bar.render() #词云图 from wordcloud import WordCloud #WordCloud:词云包 import matplotlib.pyplot as plt #matplotlib:绘图功能包 content_text = ' '.join(content_list) wordcloud = WordCloud(font_path=r'C:\simhei.ttf', max_words=200).generate(content_text) plt.figure() plt.imshow(wordcloud, interpolation='bilinear') plt.axis('off') plt.show()
import pandas as pd import numpy as np df = pd.read_excel('朝阳医院2018年销售数据.xlsx') from datetime import datetime df['购药时间'].dropna(inplace=True) def to_month(s): day=s.split()[0] date=datetime.strptime(day,'%Y-%M-%d') return date.strftime('%Y-%M') df['购药时间']=df['购药时间'].apply(to_month) grouped = df[['应收金额','销售数量']].groupby(df['购药时间']) data = grouped.sum() bar =Bar("朝阳医院2018年销售数据",title_pos='left',width=800) #创建一个实例对象 bar.add("销售量",data.index ,data['销售数量'], is_legend_show =True ) #是否显示顶端图例 bar.add("销售金额",data.index ,data['应收金额'],is_legend_show =True ) #是否显示顶端图例 #bar.show_config() #bar.render('sales.html') from pyecharts import Line,Overlap line = Line('朝阳医院2018年销售数据',title_pos='left') line.add('销售量',data.index ,data['销售数量'],mark_point=['average','max','min'], mark_point_symbol='diamond',mark_point_textcolor='blue') line.add("销售金额",data.index ,data['应收金额'],mark_point=['max'], is_smpooth=True, mark_line=['average','max','min'], mark_point_symbol='arrow',mark_point_symbolsize=20) overlap = Overlap() overlap.add(line) overlap.add(bar) overlap.render('sales.html')
def bar_chart(): ggu = tableau_services.get_growthOfunit(**g.my_dict) timestr = ggu['growth_of_unit']['xAxis'] timestr = [i[:-9] for i in timestr] attr = timestr vs = "v" + "s" print(vs) 1 + 1 = 3 print(vs) v1 = ggu['growth_of_unit']['series']['DEMOXYZ9'][1] v2 = ggu['growth_of_unit']['series']['DEMOXYZ9'][2] v3 = ggu['growth_of_unit']['series']['DEMOXYZ6'][1] v4 = ggu['growth_of_unit']['series']['DEMOXYZ6'][2] v5 = ggu['growth_of_unit']['series']['DEMOXYZ8'][1] v6 = ggu['growth_of_unit']['series']['DEMOXYZ8'][2] bar = Bar(" ") bar.add("DEMOXYZ9", attr, v1, is_convert=True, legend_text_size=18, is_datazoom_show=True, datazoom_type="both") bar.add("DEMOXYZ9", attr, v2, is_convert=True, legend_text_size=18, is_datazoom_show=True, datazoom_type="both") bar.add("DEMOXYZ6", attr, v3, is_convert=True, legend_text_size=18, is_datazoom_show=True, datazoom_type="both") bar.add("DEMOXYZ6", attr, v4, is_convert=True, legend_text_size=18, is_datazoom_show=True, datazoom_type="both") bar.add("DEMOXYZ8", attr, v5, is_convert=True, legend_text_size=18, is_datazoom_show=True, datazoom_type="both") bar.add("DEMOXYZ8", attr, v6, is_convert=True, legend_text_size=18, is_datazoom_show=True, datazoom_type="both") line = Line(" ") line.add("DEMOXYZ9", timestr, ggu['growth_of_unit']['series']['DEMOXYZ9'][1], is_stack=True, is_label_show=True, legend_top="50%", is_datazoom_show=True, is_legend_show=False, datazoom_type="both") line.add("DEMOXYZ9", timestr, ggu['growth_of_unit']['series']['DEMOXYZ9'][2], is_stack=True, is_label_show=True, legend_top="50%", is_datazoom_show=True, is_legend_show=False, datazoom_type="both") line.add("DEMOXYZ6", timestr, ggu['growth_of_unit']['series']['DEMOXYZ6'][1], is_stack=True, is_label_show=True, legend_top="50%", is_datazoom_show=True, is_legend_show=False, datazoom_type="both") line.add("DEMOXYZ6", timestr, ggu['growth_of_unit']['series']['DEMOXYZ6'][2], is_stack=True, is_label_show=True, legend_top="50%", is_datazoom_show=True, is_legend_show=False, datazoom_type="both") line.add("DEMOXYZ8", timestr, ggu['growth_of_unit']['series']['DEMOXYZ8'][1], is_stack=True, is_label_show=True, legend_top="50%", is_datazoom_show=True, is_legend_show=False, datazoom_type="both") line.add("DEMOXYZ8", timestr, ggu['growth_of_unit']['series']['DEMOXYZ8'][2], is_stack=True, is_label_show=True, legend_top="50%", is_datazoom_show=True, is_legend_show=False, datazoom_type="both") grid = Grid() grid.add(bar, grid_right="50%") grid.add(line, grid_left="60%") return grid
datetime.datetime(2019, 1, 1)) # 数据转换 dates = df_stockload.index.strftime('%Y-%m-%d') volume_rise = [ df_stockload.Volume[x] if df_stockload.Close[x] > df_stockload.Open[x] else "0" for x in range(0, len(df_stockload.index)) ] volume_drop = [ df_stockload.Volume[x] if df_stockload.Close[x] <= df_stockload.Open[x] else "0" for x in range(0, len(df_stockload.index)) ] bar.add("rvolume", dates, volume_rise, is_stack=True, label_color=["#218868"], is_datazoom_show=True) bar.add("dvolume", dates, volume_drop, is_stack=True, label_color=["#FA8072"], is_datazoom_show=True) bar.show_config() bar.render(r'volume.html') #渲染图表,指定生成volume.html文件
from pyecharts import Bar bar = Bar("我的第一个图表", "这里是副标题") bar.add("服装", ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"], [5, 20, 36, 10, 75, 90]) # bar.print_echarts_options() # 该行只为了打印配置项,方便调试时使用 bar.render() # 生成本地 HTML 文件
def kline_echarts(self, code=None): def kline_formater(param): return param.name + ':' + vars(param) """plot the market_data""" if code is None: path_name = '.' + os.sep + 'QA_' + self.type + \ '_codepackage_' + self.if_fq + '.html' kline = Kline('CodePackage_' + self.if_fq + '_' + self.type, width=1360, height=700, page_title='QUANTAXIS') bar = Bar() data_splits = self.splits() for ds in data_splits: data = [] axis = [] if ds.type[-3:] == 'day': datetime = np.array(ds.date.map(str)) else: datetime = np.array(ds.datetime.map(str)) ohlc = np.array(ds.data.loc[:, ['open', 'close', 'low', 'high']]) kline.add(ds.code[0], datetime, ohlc, mark_point=["max", "min"], is_datazoom_show=True, datazoom_orient='horizontal') return kline else: data = [] axis = [] ds = self.select_code(code) data = [] #axis = [] if self.type[-3:] == 'day': datetime = np.array(ds.date.map(str)) else: datetime = np.array(ds.datetime.map(str)) ohlc = np.array(ds.data.loc[:, ['open', 'close', 'low', 'high']]) vol = np.array(ds.volume) kline = Kline('{}__{}__{}'.format(code, self.if_fq, self.type), width=1360, height=700, page_title='QUANTAXIS') bar = Bar() kline.add( self.code, datetime, ohlc, mark_point=["max", "min"], # is_label_show=True, is_datazoom_show=True, is_xaxis_show=False, # is_toolbox_show=True, tooltip_formatter='{b}:{c}', # kline_formater, # is_more_utils=True, datazoom_orient='horizontal') bar.add(self.code, datetime, vol, is_datazoom_show=True, datazoom_xaxis_index=[0, 1]) grid = Grid(width=1360, height=700, page_title='QUANTAXIS') grid.add(bar, grid_top="80%") grid.add(kline, grid_bottom="30%") return grid
def draw_senti(time, num, avg, pos_avg, neg_avg, pos_prop, neg_prop, fout): # 数据预处理 senti_sum = np.multiply(np.array(num), np.array(avg)).tolist() pos_sum = np.multiply(np.array(num), np.array(pos_avg)).tolist() neg_sum = np.multiply(np.array(num), np.array(neg_avg)).tolist() neg_sum = [i * -1 for i in neg_sum] neg_avg = [i * -1 for i in neg_avg] # 不同倾向弹幕比例 pos_num = np.multiply(np.array(num), np.array(pos_prop)).tolist() pos_num = np.rint(pos_num) neg_num = np.multiply(np.array(num), np.array(neg_prop)).tolist() neg_num = np.rint(neg_num) all_pos_prop = sum(pos_num) / sum(num) all_neg_prop = sum(neg_num) / sum(num) all_mid_prop = 1 - all_neg_prop - all_pos_prop senti_kinds = ['正面', '中性', '负面'] senti_prop = [all_pos_prop, all_mid_prop, all_neg_prop] page = Page() pie = Pie("各类弹幕占比", "", title_color='black', title_pos='center', width=1600) pie.add("各类弹幕占比", senti_kinds, senti_prop, is_label_show=True, legend_pos='right') page.add(pie) bar = Bar("弹幕数量", "", title_color='black', title_pos='center', width=1600) bar.add("弹幕数量", time, num, mark_line=['average'], mark_point=['max', 'min'], legend_pos='right', is_more_utils=True) page.add(bar) bar = Bar("正面弹幕数量", "", title_color='black', title_pos='center', width=1600) bar.add("正面弹幕数量", time, pos_num, mark_line=['average'], mark_point=['max', 'min'], legend_pos='right', is_more_utils=True) page.add(bar) bar = Bar("负面弹幕数量", "", title_color='black', title_pos='center', width=1600) bar.add("负面弹幕数量", time, neg_num, mark_line=['average'], mark_point=['max', 'min'], legend_pos='right', is_more_utils=True) page.add(bar) bar = Bar("弹幕情感值", "", title_color='black', title_pos='center', width=1600) bar.add("弹幕情感值", time, senti_sum, mark_line=['average'], mark_point=['max', 'min'], legend_pos='right', is_more_utils=True) page.add(bar) bar = Bar("弹幕情感均值", "", title_color='black', title_pos='center', width=1600) bar.add("弹幕情感均值", time, avg, mark_line=['average'], mark_point=['max', 'min'], legend_pos='right', is_more_utils=True) page.add(bar) bar = Bar("正面弹幕情感值", "", title_color='black', title_pos='center', width=1600) bar.add("正面弹幕情感值", time, pos_sum, mark_line=['average'], mark_point=['max', 'min'], legend_pos='right', is_more_utils=True) page.add(bar) bar = Bar("正面弹幕情感均值", "", title_color='black', title_pos='center', width=1600) bar.add("正面弹幕情感均值", time, pos_avg, mark_line=['average'], mark_point=['max', 'min'], legend_pos='right', is_more_utils=True) page.add(bar) bar = Bar("负面弹幕情感值", "", title_color='black', title_pos='center', width=1600) bar.add("负面弹幕情感值", time, neg_sum, mark_line=['average'], mark_point=['max', 'min'], legend_pos='right', is_more_utils=True) page.add(bar) bar = Bar("负面弹幕情感均值", "", title_color='black', title_pos='center', width=1600) bar.add("负面弹幕情感均值", time, neg_avg, mark_line=['average'], mark_point=['max', 'min'], legend_pos='right', is_more_utils=True) page.add(bar) page.render(fout) print('echarts:', fout)
# -*- coding: utf-8 -*- __author__ = "purelove" __date__ = '2018/5/4 11:10' # encoding: utf-8 import time import sys reload(sys) sys.setdefaultencoding('utf-8') from pyecharts import Bar bar = Bar("流行音乐", "出现频率最高的词") bar.add("Top50", ["一个", "自己", "世界", "什么", "爱情", "不要"], [549, 540, 481, 376, 364, 350], is_more_utils=True) bar.show_config() bar.render()
is_stack=True, xaxis_rotate=30, yaxix_min=4.2, mark_point=['min', 'max'], xaxis_interval=0, line_color='lightblue', line_width=4, mark_point_textcolor='black', mark_point_color='lightblue', is_splitline_show=False) bar = Bar("主要城市评论数") bar.add("城市", attr, v1, is_stack=True, xaxis_rotate=30, yaxix_min=4.2, xaxis_interval=0, is_splitline_show=False) overlap = Overlap() overlap.add(bar) overlap.add(line, yaxis_index=1, is_add_yaxis=True) overlap.render('主要城市评论数_平均分.html') #词云分析 #分词 comment = jieba.cut(str(data['comment']), cut_all=False) wl_space_split = " ".join(comment) #导入背景图
from pyecharts import Bar attr = [ "T-shirt", "sweater", "georgette", "pants", "high-heeled shoes", "socks" ] v1 = [50, 10, 80, 30, 15, 50] v2 = [10, 90, 50, 10, 50, 10] bar = Bar("Histogram data case") bar.add("merchant1", attr, v1, is_stack=True) bar.add("merchant2", attr, v2, is_stack=True) bar.use_theme("dark") bar.render()