def html_handle(self, data): """ convert function to html by pyecharts Args: data(dict): the data info Returns: chart: chart generated by pyecharts: Bar, Pie, Line or Scatter filename: html file name """ filename = self.table_name + str(data['order']) + '.html' margin = str(data['title_top']) + '%' # 设置图标基本属性 if data['chart'] == 'bar': chart = (Bar().set_series_opts(label_opts=opts.LabelOpts( is_show=False)).set_global_opts( title_opts=opts.TitleOpts(title=data['chartname'], subtitle=data['describe'], pos_left='center', pos_top=margin), xaxis_opts=opts.AxisOpts(name=data['x_name']), yaxis_opts=opts.AxisOpts( name=data['y_name'], splitline_opts=opts.SplitLineOpts(is_show=True)))) elif data['chart'] == 'pie': chart = (Pie().set_global_opts( title_opts=opts.TitleOpts(title=data['chartname'], subtitle=data['describe'], pos_left='center', pos_top=margin))) elif data['chart'] == 'line': chart = (Line().set_series_opts(label_opts=opts.LabelOpts( is_show=False)).set_global_opts( title_opts=opts.TitleOpts(title=data['chartname'], subtitle=data['describe'], pos_left='center', pos_top=margin), xaxis_opts=opts.AxisOpts(name=data['x_name']), yaxis_opts=opts.AxisOpts( name=data['y_name'], splitline_opts=opts.SplitLineOpts(is_show=True)))) elif data['chart'] == 'scatter': chart = (Scatter().set_series_opts(label_opts=opts.LabelOpts( is_show=False)).set_global_opts( title_opts=opts.TitleOpts(title=data['chartname'], subtitle=data['describe'], pos_left='center', pos_top=margin), xaxis_opts=opts.AxisOpts( type_='value', name=data['x_name'], splitline_opts=opts.SplitLineOpts(is_show=True)), yaxis_opts=opts.AxisOpts( type_='value', name=data['y_name'], splitline_opts=opts.SplitLineOpts(is_show=True)))) else: print("not valid chart") if not data["classify"]: # 在图片上只需展示一组数据 attr = data["x_data"][0] # 横坐标 val = data["y_data"][0] # 纵坐标 if data['chart'] == 'bar': chart.add_xaxis(attr).add_yaxis( "", val, label_opts=opts.LabelOpts(is_show=False)) elif data['chart'] == 'line': chart.add_xaxis(attr).add_yaxis( "", val, label_opts=opts.LabelOpts(is_show=False)) elif data['chart'] == 'pie': chart.add("", [list(z) for z in zip(attr, val)]) elif data['chart'] == 'scatter': if isinstance(attr[0], str): attr = [x for x in attr if x != ''] attr = list(map(float, attr)) if isinstance(val[0], str): val = [x for x in val if x != ''] val = list(map(float, val)) chart.add_xaxis(attr).add_yaxis( "", val, label_opts=opts.LabelOpts(is_show=False)) else: # 在图片上需要展示多组数据 attr = data["x_data"][0] # 横坐标 for i in range(len(data["classify"])): # 循环输出每组数据 val = data["y_data"][i] # 每组纵坐标的值 name = (data["classify"][i][0] if type(data["classify"][i]) == type(('a', 'b')) else data["classify"][i]) if i == 0: if data['chart'] != 'pie' and data['chart'] != 'scatter': chart.add_xaxis(attr) if data['chart'] == 'bar': chart.add_yaxis(name, val, stack="stack1", label_opts=opts.LabelOpts(is_show=False)) elif data['chart'] == 'line': chart.add_yaxis(name, val, label_opts=opts.LabelOpts(is_show=False)) elif data['chart'] == 'pie': chart.add("", [list(z) for z in zip(attr, val)]) elif data['chart'] == 'scatter': attr_scatter = data["x_data"][i] if isinstance(attr_scatter[0], str): # 去除散点图的空点,并将字符类型转化为数字类型 attr_scatter = [x for x in attr_scatter if x != ''] attr_scatter = list(map(float, attr_scatter)) if isinstance(val[0], str): val = [x for x in val if x != ''] val = list(map(float, val)) chart.add_xaxis(attr_scatter).add_yaxis( name, val, label_opts=opts.LabelOpts(is_show=False)) return chart, filename
[2411, 2433.13, 2403.3, 2437.42], [2432.68, 2334.48, 2427.7, 2441.73], [2430.69, 2418.53, 2394.22, 2433.89], [2416.62, 2432.4, 2414.4, 2443.03], [2441.91, 2421.56, 2418.43, 2444.8], [2420.26, 2382.91, 2373.53, 2427.07], [2383.49, 2397.18, 2370.61, 2397.94], [2378.82, 2325.95, 2309.17, 2378.82], [2322.94, 2314.16, 2308.76, 2330.88], [2320.62, 2325.82, 2315.01, 2338.78], [2313.74, 2293.34, 2289.89, 2340.71], [2297.77, 2313.22, 2292.03, 2324.63], [2322.32, 2365.59, 2308.92, 2366.16], [2364.54, 2359.51, 2330.86, 2369.65], [2332.08, 2273.4, 2259.25, 2333.54], [2274.81, 2326.31, 2270.1, 2328.14], [2333.61, 2347.18, 2321.6, 2351.44], [2340.44, 2324.29, 2304.27, 2352.02], [2326.42, 2318.61, 2314.59, 2333.67], [2314.68, 2310.59, 2296.58, 2320.96], [2309.16, 2286.6, 2264.83, 2333.29], [2282.17, 2263.97, 2253.25, 2286.33], [2255.77, 2270.28, 2253.31, 2276.22], ] c = (Kline().add_xaxis(["2017/7/{}".format(i + 1) for i in range(31) ]).add_yaxis("kline", data).set_global_opts( yaxis_opts=opts.AxisOpts(is_scale=True), xaxis_opts=opts.AxisOpts(is_scale=True), title_opts=opts.TitleOpts(title="Kline-基本示例"), ).render("5.kline_base.html"))
def show_czsc(name: str, contract, levels: [QuoteLevel]): quotes, raw_df = get_all_quotes(contract, levels[0]) # macd = MACD() traders = [ThirdTradeTrader(FIVE_MINUTE), ThirdTradeTrader(THIRTY_MINUTE)] czsc = Czsc(quotes, levels[0], levels, traders, traders, traders) # raw quotes candle x_data = [quote.timestamp for quote in quotes] y_data = [[quote.open, quote.close, quote.low, quote.high] for quote in quotes] candle = Candlestick( init_opts=opts.InitOpts(width="1300px", height="600px")) candle.add_xaxis(xaxis_data=x_data) candle.add_yaxis(series_name="raw_quotes_" + levels[0].label, y_axis=y_data) candle.set_series_opts() candle.set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), datazoom_opts=[opts.DataZoomOpts(type_="inside")], title_opts=opts.TitleOpts(title="Kline-ItemStyle"), ) # czsc drawing lines drawings = czsc.get_drawings() line = Line() x_drawing = [p.quote.timestamp for p in drawings] y_drawing = [p.value() for p in drawings] line.add_xaxis(xaxis_data=x_drawing) line.add_yaxis(series_name=czsc.raw_level.label + "_draw", y_axis=y_drawing) candle.overlap(line) # czsc segments for level in levels: segments = czsc.get_segments(level) segment_line = Line() x_segment = [p.quote.timestamp for p in segments] y_segment = [p.value() for p in segments] segment_line.add_xaxis(xaxis_data=x_segment) segment_line.add_yaxis(series_name=level.label, y_axis=y_segment) candle.overlap(segment_line) for trader in traders: trading_point_chart_bottom = EffectScatter() trading_point_chart_bottom.add_xaxis([ point.quote.timestamp for point in trader.open_points if point.point_type is PointType.BOTTOM ]) trading_point_chart_bottom.add_yaxis(trader.level.label + "_trade", [ point.value() for point in trader.open_points if point.point_type is PointType.BOTTOM ], symbol=SymbolType.TRIANGLE) candle.overlap(trading_point_chart_bottom) trading_point_chart_top = EffectScatter() trading_point_chart_top.add_xaxis([ point.quote.timestamp for point in trader.open_points if point.point_type is PointType.TOP ]) trading_point_chart_top.add_yaxis(trader.level.label + "_trade", [ point.value() for point in trader.open_points if point.point_type is PointType.TOP ], symbol=SymbolType.ARROW) candle.overlap(trading_point_chart_top) close_point_chart = EffectScatter() close_point_chart.add_xaxis( [point.quote.timestamp for point in trader.close_points]) close_point_chart.add_yaxis( trader.level.label + "_trade", [point.value() for point in trader.close_points]) candle.overlap(close_point_chart) # maincenters for level in levels: maincenters = czsc.get_maincenters(level) for maincenter in maincenters: rectangle = Line() x = [ maincenter.start, maincenter.end, maincenter.end, maincenter.start, maincenter.start ] y = [ maincenter.bottom, maincenter.bottom, maincenter.top, maincenter.top, maincenter.bottom ] rectangle.add_xaxis(xaxis_data=x) rectangle.add_yaxis(y_axis=y, series_name="maincenter_" + level.label) candle.overlap(rectangle) # show candle.render(name)
def kaohsiung_page(): try: db = MySQLdb.connect(host='127.0.0.1', user='******', passwd='20200428', db='fruveg', port=3307, charset='utf8') cursor = db.cursor() db.autocommit(True) Item_No = "A1" # 香蕉 market_list = [["830", "高雄", "鳳山區", "Kaohsiung_Banana.html"], ["800", "高雄", "高雄市", "Kaohsiung_Banana.html"]] for market_index in range(0, len(market_list), 2): yesterday = (datetime.now() - timedelta(days=1)).strftime('%Y/%m/%d') # 取得2012~昨天所有西元日期放入List trade_date, 並設定為Line Chart及Bar Chart的X軸 sql = """Select DATE_FORMAT(WDate, '%Y/%m/%d') as WDate From date_map Where wdate between '2012/01/01' and '""" + yesterday + """' Order by WDate;""" cursor.execute(sql) datarows = cursor.fetchall() trade_date_1 = [row[0] for row in datarows] # 依果菜市場代碼取得2012~昨天[每天]的交易平均單價及交易量 # 並放入List avg_price trade_amount, 並加入Line Chart 及 Bar Chart Y軸系列 sql = """Select a.trade_date, b.market_no, b.avg_price, b.trade_amount From (Select wDate as trade_date From date_map Where wdate between '2012/01/01' and '%s') a Left Join (Select trade_date, market_no, avg_price, trade_amount From trade_raws Where item_no='%s' and market_no='%s' and trade_date between '2012/01/01' and '%s') b on a.trade_date=b.trade_date order by a.trade_date;""" % (yesterday, Item_No, market_list[market_index][0], yesterday) cursor.execute(sql) datarows = cursor.fetchall() avg_price_1 = [row[2] for row in datarows] trade_amount_1 = [row[3] for row in datarows] # 設定Line Chart屬性 linechart_1 = ( Line( init_opts=opts.InitOpts(width="100%", height="400px") ) .add_xaxis(trade_date_1) .add_yaxis( "平均價格(NT$)", avg_price_1, is_connect_nones=True, label_opts=opts.LabelOpts(is_show=False) ) # 因後續Line Chart要合併Bar Chart, 在此新增Line Chart右邊X軸的刻度 # 為了讓平均價格趨勢線及成交量合併後畫面的好看, 因此定義右邊X軸的最小及最大刻度 .extend_axis( yaxis=opts.AxisOpts( name="交易量(公斤)", type_="value", min_=0, max_=80000, interval=10000, axislabel_opts=opts.LabelOpts(formatter="{value}"), ) ) .set_global_opts( title_opts=opts.TitleOpts("%s果菜市場\n香蕉每日批發平均價格及交易量" % market_list[market_index][2], pos_left="center"), datazoom_opts=opts.DataZoomOpts(type_="slider", range_start=97, range_end=100), legend_opts=opts.LegendOpts(is_show=False), tooltip_opts=opts.TooltipOpts(is_show=True, axis_pointer_type="cross"), yaxis_opts=opts.AxisOpts( name="新台幣(元)", splitline_opts=opts.SplitLineOpts(is_show=True), ), ) ) # 設定Bar Chart屬性 barchart_1 = ( Bar(init_opts=opts.InitOpts(width="100%", height="150px")) .add_xaxis(trade_date_1) .add_yaxis( "成交量(公斤)", trade_amount_1, yaxis_index=1, color="#00E3E3", label_opts=opts.LabelOpts(is_show=False) ) .set_global_opts( datazoom_opts=opts.DataZoomOpts(type_="slider", range_start=97, range_end=100), legend_opts=opts.LegendOpts(is_show=False), tooltip_opts=opts.TooltipOpts(is_show=True), yaxis_opts=opts.AxisOpts( name="公斤", splitline_opts=opts.SplitLineOpts(is_show=True), ), ) ) # 合併Line Chart及Bar Chart # linechart.overlap(barchart).render("Taipei_Banana.html") myoverlap_1 = linechart_1.overlap(barchart_1) today = datetime.now().strftime('%Y/%m/%d') t30 = (datetime.now() + timedelta(days=30)).strftime('%Y/%m/%d') # 產生今天起30天預測線Line Chart 並加入List pred_date sql = """Select Date_Format(WDate, '%Y/%m/%d') as WDate From date_map Where WDate Between '""" + today + """' and '""" + t30 + """' Order by WDate;""" cursor.execute(sql) datarows = cursor.fetchall() pred_date_1 = [WDate[0] for WDate in datarows] # 產生30筆20~50之間的亂數做為虛擬的預測平均價格, 放入List pred_price pred_price_1 = [random.randrange(20, 50) for i in range(1, 31)] pred_linechart_1 = ( Line(init_opts=opts.InitOpts(width="100%", height="250px")) .add_xaxis(pred_date_1) .add_yaxis( "預測平均價格(NT$)", pred_price_1, is_connect_nones=True, label_opts=opts.LabelOpts(is_show=False) ) .set_global_opts( title_opts=opts.TitleOpts("[預測]%s果菜市場\n香蕉批發平均價格及交易量" % market_list[market_index][2], pos_left="center"), # datazoom_opts=opts.DataZoomOpts(type_="slider", range_start=97, range_end=100), legend_opts=opts.LegendOpts(is_show=False), tooltip_opts=opts.TooltipOpts(is_show=True, axis_pointer_type="cross"), yaxis_opts=opts.AxisOpts( name="新台幣(元)", splitline_opts=opts.SplitLineOpts(is_show=True), ), ) ) # 以上完成區域第一個市場 # ----------------------------------------------------------------------------------------------------------- # 以下開始區域第二個市場 trade_date_2 = trade_date_1 # 依果菜市場代碼取得2012~昨天[每天]的交易平均單價及交易量 # 並放入List avg_price trade_amount, 並加入Line Chart 及 Bar Chart Y軸系列 sql = """Select a.trade_date, b.market_no, b.avg_price, b.trade_amount From (Select wDate as trade_date From date_map Where wdate between '2012/01/01' and '%s') a Left Join (Select trade_date, market_no, avg_price, trade_amount From trade_raws Where item_no='%s' and market_no='%s' and trade_date between '2012/01/01' and '%s') b on a.trade_date=b.trade_date order by a.trade_date;""" % (yesterday, Item_No, market_list[market_index + 1][0], yesterday) cursor.execute(sql) datarows = cursor.fetchall() avg_price_2 = [row[2] for row in datarows] trade_amount_2 = [row[3] for row in datarows] # 設定Line Chart屬性 linechart_2 = ( Line( init_opts=opts.InitOpts(width="100%", height="400px") ) .add_xaxis(trade_date_2) .add_yaxis( "平均價格(NT$)", avg_price_2, is_connect_nones=True, label_opts=opts.LabelOpts(is_show=False) ) # 因後續Line Chart要合併Bar Chart, 在此新增Line Chart右邊X軸的刻度 # 為了讓平均價格趨勢線及成交量合併後畫面的好看, 因此定義右邊X軸的最小及最大刻度 .extend_axis( yaxis=opts.AxisOpts( name="交易量(公斤)", type_="value", min_=0, max_=80000, interval=10000, axislabel_opts=opts.LabelOpts(formatter="{value}"), ) ) .set_global_opts( title_opts=opts.TitleOpts("%s果菜市場\n香蕉每日批發平均價格及交易量" % market_list[market_index + 1][2], pos_left="center"), datazoom_opts=opts.DataZoomOpts(type_="slider", range_start=97, range_end=100), legend_opts=opts.LegendOpts(is_show=False), tooltip_opts=opts.TooltipOpts(is_show=True, axis_pointer_type="cross"), yaxis_opts=opts.AxisOpts( name="新台幣(元)", splitline_opts=opts.SplitLineOpts(is_show=True), ), ) ) # 設定Bar Chart屬性 barchart_2 = ( Bar(init_opts=opts.InitOpts(width="100%", height="150px")) .add_xaxis(trade_date_1) .add_yaxis( "成交量(公斤)", trade_amount_2, yaxis_index=1, color="#00E3E3", label_opts=opts.LabelOpts(is_show=False) ) .set_global_opts( datazoom_opts=opts.DataZoomOpts(type_="slider", range_start=97, range_end=100), legend_opts=opts.LegendOpts(is_show=False), tooltip_opts=opts.TooltipOpts(is_show=True), yaxis_opts=opts.AxisOpts( name="公斤", splitline_opts=opts.SplitLineOpts(is_show=True), ), ) ) # 合併Line Chart及Bar Chart # linechart.overlap(barchart).render("Taipei_Banana.html") myoverlap_2 = linechart_2.overlap(barchart_2) # 產生預測線Line Chart pred_date_2 = pred_date_1 # 產生30筆25~50之間的亂數做為虛擬的預測平均價格, 放入List pred_price pred_price_2 = [random.randrange(25, 50) for i in range(1, 31)] pred_linechart_2 = ( Line(init_opts=opts.InitOpts(width="100%", height="250px")) .add_xaxis(pred_date_2) .add_yaxis( "預測平均價格(NT$)", pred_price_2, is_connect_nones=True, label_opts=opts.LabelOpts(is_show=False) ) .set_global_opts( title_opts=opts.TitleOpts("[預測]%s果菜市場\n香蕉批發平均價格及交易量" % market_list[market_index + 1][2], pos_left="center"), # datazoom_opts=opts.DataZoomOpts(type_="slider", range_start=97, range_end=100), legend_opts=opts.LegendOpts(is_show=False), tooltip_opts=opts.TooltipOpts(is_show=True, axis_pointer_type="cross"), yaxis_opts=opts.AxisOpts( name="新台幣(元)", splitline_opts=opts.SplitLineOpts(is_show=True), ), ) ) # 以上完成區域第二個市場 # ---------------------------------------------------------------------------------------------------------- # 以下將兩個市場的圖合併在一個網頁中 mypage = ( Page(page_title="%s" % market_list[market_index][1]) .add(myoverlap_1, pred_linechart_1) .add(myoverlap_2, pred_linechart_2) ) mypage.render(r"./static/%s" % market_list[market_index][3]) except Exception as Err: print(Err) db.close()
# 看评论量走势和时间的关系。 df['时间'] = df.评论时间.str.split('-').str[1] + '-' + df.评论时间.str.split('-').str[2] # print(df.head()) # 下面用冒号:分割‘时间’这栏的数据就能得到我们需要的日期和小时的数据 df['时间'] = df.时间.str.split(':').str[0] time_num = df.时间.value_counts().sort_index() time_num[:5] print(time_num[:5]) # 用下面两行代码设定横坐标为时间,纵坐标表示评论数量。 # 产生数据 x1_line1 = time_num.index.values.astype('str').tolist() y1_line1 = time_num.values.tolist() # 绘制面积图 line1 = Line(init_opts=opts.InitOpts(width='1350px', height='750px')) line1.add_xaxis(x1_line1) line1.add_yaxis('', y1_line1, areastyle_opts=opts.AreaStyleOpts(opacity=0.3), markpoint_opts=opts.MarkPointOpts( data=[opts.MarkPointItem(type_='max', name='最大值')])) line1.set_global_opts( title_opts=opts.TitleOpts('各个时段评论人数'), xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate='30'))) line1.set_series_opts(label_opts=opts.LabelOpts(is_show=False), axisline_opts=opts.AxisLineOpts()) line1.render( ) # replace the file:///C:/Users/Maggie/Desktop/Udemy-desktop/xiaoxiangxueyuan/pythonCases/xiaoxiang_projects/python_in_16_days/render.html # #从5月20日8:30发布MV后,评论数量逐渐上升,12点左右有一个快速增加,达到高峰。后续随着时间的推移,评论人数逐渐减少,趋于平缓。
[2274.81, 2326.31, 2270.1, 2328.14], [2333.61, 2347.18, 2321.6, 2351.44], [2340.44, 2324.29, 2304.27, 2352.02], [2326.42, 2318.61, 2314.59, 2333.67], [2314.68, 2310.59, 2296.58, 2320.96], [2309.16, 2286.6, 2264.83, 2333.29], [2282.17, 2263.97, 2253.25, 2286.33], [2255.77, 2270.28, 2253.31, 2276.22], ] c = ( Kline() .add_xaxis(["2017/7/{}".format(i + 1) for i in range(31)]) .add_yaxis("kline", data) .set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1) ), ), datazoom_opts=[opts.DataZoomOpts(pos_bottom="-2%")], title_opts=opts.TitleOpts(title="Kline-DataZoom-slider-Position"), ) ) c.width = "100%" put_html(c.render_notebook())
93.58695857541488, 101.4126683297632, 108.48378461530217, 114.49355390682695, 119.16795429637915, 122.27931702317058, 123.65837448506679, 123.20413594805603, 120.89107255501017, 116.7731992576505, 110.98476877890735, ] (Bar(init_opts=opts.InitOpts(width="1600px", height="800px")).add_xaxis( xaxis_data=category).add_yaxis( series_name="bar", yaxis_data=red_bar, label_opts=opts.LabelOpts(is_show=False)).add_yaxis( series_name="bar2", yaxis_data=blue_bar, label_opts=opts.LabelOpts(is_show=False), ).set_global_opts( title_opts=opts.TitleOpts(title="柱状图动画延迟"), xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts( is_show=False)), yaxis_opts=opts.AxisOpts( axistick_opts=opts.AxisTickOpts(is_show=True), splitline_opts=opts.SplitLineOpts(is_show=True), ), ).render("bar_chart_display_delay.html"))
def generate_a_view(data): # 设置图标基本属性 margin = '5%' if data['chart'] == 'bar': chart = (Bar().set_series_opts(label_opts=opts.LabelOpts( is_show=False)).set_global_opts( title_opts=opts.TitleOpts(title=data['chartname'], subtitle=data['describe'], pos_left='center', pos_top=margin), xaxis_opts=opts.AxisOpts(name=data['x_name']), yaxis_opts=opts.AxisOpts( name=data['y_name'], splitline_opts=opts.SplitLineOpts(is_show=True)))) elif data['chart'] == 'pie': chart = (Pie().set_global_opts( title_opts=opts.TitleOpts(title=data['chartname'], subtitle=data['describe'], pos_left='center', pos_top=margin))) elif data['chart'] == 'line': chart = (Line().set_series_opts(label_opts=opts.LabelOpts( is_show=False)).set_global_opts( title_opts=opts.TitleOpts(title=data['chartname'], subtitle=data['describe'], pos_left='center', pos_top=margin), xaxis_opts=opts.AxisOpts(name=data['x_name']), yaxis_opts=opts.AxisOpts( name=data['y_name'], splitline_opts=opts.SplitLineOpts(is_show=True)))) elif data['chart'] == 'scatter': chart = (Scatter().set_series_opts(label_opts=opts.LabelOpts( is_show=False)).set_global_opts( title_opts=opts.TitleOpts(title=data['chartname'], subtitle=data['describe'], pos_left='center', pos_top=margin), xaxis_opts=opts.AxisOpts( type_='value', name=data['x_name'], splitline_opts=opts.SplitLineOpts(is_show=True)), yaxis_opts=opts.AxisOpts( type_='value', name=data['y_name'], splitline_opts=opts.SplitLineOpts(is_show=True)))) else: print("not valid chart") # 添加数据 attr = data["x_data"] # 横坐标 val = data["y_data"] # 纵坐标 if data['chart'] == 'bar': chart.add_xaxis(attr).add_yaxis( "", val, label_opts=opts.LabelOpts(is_show=False)) elif data['chart'] == 'line': chart.add_xaxis(attr).add_yaxis( "", val, label_opts=opts.LabelOpts(is_show=False)) elif data['chart'] == 'pie': chart.add("", [list(z) for z in zip(attr, val)]) elif data['chart'] == 'scatter': if isinstance(attr[0], str): attr = [x for x in attr if x != ''] attr = list(map(float, attr)) if isinstance(val[0], str): val = [x for x in val if x != ''] val = list(map(float, val)) chart.add_xaxis(attr).add_yaxis( "", val, label_opts=opts.LabelOpts(is_show=False)) return chart
import datetime import math import pyecharts.options as opts import random from pyecharts.charts import * from pyecharts.components import Table from pyecharts.faker import POPULATION from pyecharts.globals import CurrentConfig CurrentConfig.ONLINE_HOST = "https://cdn.kesci.com/lib/pyecharts_assets/" # %% # 直角坐标系图表 # 直方图 x_data = ['apple', 'huawei', 'xiaomi', 'oppo', 'vivo', 'meizu'] y_data = [123, 312, 89, 107, 82, 23] bar = (Bar().add_xaxis(x_data).add_yaxis('', y_data)) bar.render() # %% # 折线图 x_data = ['apple', 'huawei', 'xiaomi', 'oppo', 'vivo', 'meizu'] y_data = [123, 312, 89, 107, 82, 23] bar = (Line().add_xaxis(x_data).add_yaxis('', y_data)) bar.render() # %% # 折线图 x_data = ['apple', 'huawei', 'xiaomi', 'oppo', 'vivo', 'meizu'] y_data = [[random.randint(100, 200) for i in range(10)] for item in x_data] Box = Boxplot() Box.add_xaxis(x_data) Box.add_yaxis('', Box.prepare_data(y_data)) bar.render()
from pyecharts import options as opts from pyecharts.charts import Bar, Line from pyecharts.faker import Faker 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().add_xaxis(Faker.months).add_yaxis("蒸发量", v1).add_yaxis( "降水量", v2).extend_axis(yaxis=opts.AxisOpts( axislabel_opts=opts.LabelOpts( formatter="{value} °C"), interval=5)).set_series_opts( label_opts=opts.LabelOpts(is_show=False)).set_global_opts( title_opts=opts.TitleOpts(title="Overlap-bar+line"), yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts( formatter="{value} ml")), )) line = Line().add_xaxis(Faker.months).add_yaxis("平均温度", v3, yaxis_index=1) bar.overlap(line) bar.render("overlap_bar_line.html")
hubei_statis = statistics__data['湖北'] # 湖北以外的新增趋势 other_statis = [all_statis[i] - hubei_statis[i] for i in range(len(dateId))] line = Line() line.add_xaxis(dateId) line.add_yaxis("全国新增确诊病例", #图例 all_statis, #数据 is_smooth=True, #是否平滑曲线 linestyle_opts=opts.LineStyleOpts(width=4, color='#B44038'),#线样式配置项 itemstyle_opts=opts.ItemStyleOpts(color='#B44038', #图元样式配置项 border_color="#B44038", #颜色 border_width=10)) #图元的大小 line.add_yaxis("湖北新增确诊病例", hubei_statis, is_smooth=True, linestyle_opts=opts.LineStyleOpts(width=2, color='#4E87ED'), label_opts=opts.LabelOpts(position='bottom'), #标签在折线的底部 itemstyle_opts=opts.ItemStyleOpts(color='#4E87ED', border_color="#4E87ED", border_width=3)) line.add_yaxis("其他省份新增病例", other_statis, is_smooth=True, linestyle_opts=opts.LineStyleOpts(width=2, color='#F1A846'), label_opts=opts.LabelOpts(position='bottom'), #标签在折线的底部 itemstyle_opts=opts.ItemStyleOpts(color='#F1A846', border_color="#F1A846", border_width=3)) line.set_global_opts(title_opts=opts.TitleOpts(title="新增确诊病例", subtitle='数据来源:丁香园'), yaxis_opts=opts.AxisOpts(max_=16000, min_=1, type_="log", #坐标轴配置项 splitline_opts=opts.SplitLineOpts(is_show=True),#分割线配置项 axisline_opts=opts.AxisLineOpts(is_show=True)))#坐标轴刻度线配置项 line.render(path='新增确诊趋势图.html')
def get_year_chart(year: int): map_data = [ [[x["name"], x["value"]] for x in d["data"]] for d in data if d["time"] == year ][0] min_data, max_data = ( min([d[1][0] for d in map_data]), max([d[1][0] for d in map_data]), ) map_chart = ( Map() .add( series_name="", data_pair=map_data, label_opts=opts.LabelOpts(is_show=False), is_map_symbol_show=False, itemstyle_opts={ "normal": {"areaColor": "#323c48", "borderColor": "#404a59"}, "emphasis": { "label": {"show": Timeline}, "areaColor": "rgba(255,255,255, 0.5)", }, }, ) .set_global_opts( title_opts=opts.TitleOpts( title="1980年以来中国各省GDP排名变化情况", subtitle="GDP单位:亿元", pos_left="center", pos_top="top", title_textstyle_opts=opts.TextStyleOpts( font_size=25, color="rgba(255,255,255, 0.9)" ), ), tooltip_opts=opts.TooltipOpts( is_show=True, formatter=JsCode( """function(params) { if ('value' in params.data) { return params.data.value[2] + ': ' + params.data.value[0]; } }""" ), ), visualmap_opts=opts.VisualMapOpts( is_calculable=True, dimension=0, pos_left="10", pos_top="center", range_text=["High", "Low"], range_color=["lightskyblue", "yellow", "orangered"], textstyle_opts=opts.TextStyleOpts(color="#ddd"), min_=min_data, max_=max_data, ), ) ) bar_x_data = [x[0] for x in map_data] # 这里注释的部分会导致 label 和 value 与 饼图不一致 # 使用下面的 List[Dict] 就可以解决这个问题了。 # bar_y_data = [x[1][0] for x in map_data] bar_y_data = [{"name": x[0], "value": x[1][0]} for x in map_data] bar = ( Bar() .add_xaxis(xaxis_data=bar_x_data) .add_yaxis( series_name="", yaxis_index=1, y_axis=bar_y_data, label_opts=opts.LabelOpts( is_show=True, position="right", formatter="{b}: {c}" ), ) .reversal_axis() .set_global_opts( xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(is_show=False)), yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(is_show=False)), tooltip_opts=opts.TooltipOpts(is_show=False), visualmap_opts=opts.VisualMapOpts( is_calculable=True, dimension=0, pos_left="10", pos_top="center", range_text=["High", "Low"], range_color=["lightskyblue", "yellow", "orangered"], textstyle_opts=opts.TextStyleOpts(color="#ddd"), min_=min_data, max_=max_data, ), graphic_opts=[ opts.GraphicGroup( graphic_item=opts.GraphicItem( rotation=JsCode("Math.PI / 4"), bounding="raw", right=110, bottom=110, z=100, ), children=[ opts.GraphicRect( graphic_item=opts.GraphicItem(left="center", top="center", z=100), graphic_shape_opts=opts.GraphicShapeOpts(width=400, height=50), graphic_basicstyle_opts=opts.GraphicBasicStyleOpts( fill="rgba(0,0,0,0.3)" ), ), opts.GraphicText( graphic_item=opts.GraphicItem(left="center", top="center", z=100), graphic_textstyle_opts=opts.GraphicTextStyleOpts( text=f"{str(year)} 年", font="bold 26px Microsoft YaHei", graphic_basicstyle_opts=opts.GraphicBasicStyleOpts(fill="#fff"), ), ), ], ) ], ) ) pie_data = [[x[0], x[1][0]] for x in map_data] percent_sum = sum([x[1][1] for x in map_data]) rest_value = 0 for d in map_data: rest_percent = 100.0 rest_percent = rest_percent - percent_sum rest_value = d[1][0] * (rest_percent / d[1][1]) pie_data.append(["其他省份", rest_value]) pie = ( Pie() .add( series_name="", data_pair=pie_data, radius=["12%", "20%"], center=["75%", "85%"], itemstyle_opts=opts.ItemStyleOpts( border_width=1, border_color="rgba(0,0,0,0.3)" ), ) .set_global_opts( tooltip_opts=opts.TooltipOpts(is_show=True, formatter="{b} {d}%"), legend_opts=opts.LegendOpts(is_show=False), ) ) grid_chart = ( Grid() .add( bar, grid_opts=opts.GridOpts( pos_left="10", pos_right="45%", pos_top="70%", pos_bottom="5" ), ) .add(pie, grid_opts=opts.GridOpts()) .add(map_chart, grid_opts=opts.GridOpts()) ) return grid_chart
def get_bar_data(request): x_field = request.GET.get('x_choice') y_field = request.GET.get('y_choice') print(request.GET.get('begin_date')) start_date = request.GET.get('begin_date').split('-') end_date = request.GET.get('end_date').split('-') start = datetime.date(int(start_date[0]), int(start_date[1]), int(start_date[2])) end = datetime.date(int(end_date[0]), int(end_date[1]), int(end_date[2])) y_lists = [] x_list = [] b = Bar() if x_field == 'street' and y_field == 'property': event_counts = Street.objects.all().values( 'name', 'number').order_by('-number') for property in properties: new_list = [property.name] for street_node in event_counts: new_len = 0 street = Street.objects.get(name=street_node['name']) for community in Community.objects.filter(street=street): new_len += len( Event.objects.filter(community=community, property=property, create_time__range=(start, end))) new_list.append(new_len) # print(new_list) y_lists.append(new_list) for street_node in event_counts: x_list.append(street_node['name']) elif x_field == 'community' and y_field == 'property': event_counts = Community.objects.all().values( 'name', 'number').order_by('-number') for property in properties: new_list = [property.name] for street_node in event_counts: community = Community.objects.get(name=street_node['name']) new_len = len( Event.objects.filter( Q(create_time__range=(start, end)) & Q(community=community) & Q(property=property))) new_list.append(new_len) # print(new_list) y_lists.append(new_list) for community_node in event_counts: x_list.append(community_node['name']) elif x_field == 'dispose_unit' and y_field == 'property': event_counts = DisposeUnit.objects.all().values( 'name', 'number').order_by('-number') for property in properties: new_list = [property.name] limit = 0 for dispose_unit_node in event_counts: dispose_unit = DisposeUnit.objects.get( name=dispose_unit_node['name']) if limit < 30: new_len = len( Event.objects.filter( Q(create_time__range=(start, end)) & Q(dispose_unit=dispose_unit) & Q(property=property))) new_list.append(new_len) new_len = 0 else: new_len += len( Event.objects.filter( Q(create_time__range=(start, end)) & Q(dispose_unit=dispose_unit) & Q(property=property))) limit += 1 new_list.append(new_len) y_lists.append(new_list) limit = 0 for dispose_unit_node in event_counts: if limit >= 30: break x_list.append(dispose_unit_node['name']) limit += 1 x_list.append("其他") elif x_field == 'main_type' and y_field == 'property': event_counts = MainType.objects.all().values( 'name', 'number').order_by('-number') for property in properties: new_list = [property.name] limit = 0 new_len = 0 for main_type_node in event_counts: main_type = MainType.objects.get(name=main_type_node['name']) for sub_type in SubType.objects.filter(main_type=main_type): new_len += len( Event.objects.filter(sub_type=sub_type, property=property, create_time__range=(start, end))) if limit < 30: limit += 1 new_list.append(new_len) new_len = 0 # print(new_list) new_list.append(new_len) y_lists.append(new_list) limit = 0 for main_type_node in event_counts: if limit >= 30: break x_list.append(main_type_node['name']) limit += 1 x_list.append('其他') elif x_field == 'sub_type' and y_field == 'property': event_counts = SubType.objects.all().values( 'name', 'number').order_by('-number') for property in properties: new_list = [property.name] limit = 0 new_len = 0 for sub_type_node in event_counts: sub_type = SubType.objects.get(name=sub_type_node['name']) new_len += len( Event.objects.filter( Q(create_time__range=(start, end)) & Q(property=property) & Q(sub_type=sub_type))) if limit < 60: limit += 1 new_list.append(new_len) new_len = 0 # print(new_list) new_list.append(new_len) y_lists.append(new_list) limit = 0 for sub_type_node in event_counts: if limit >= 60: break x_list.append(sub_type_node['name']) limit += 1 x_list.append('其他') elif x_field == 'street' and y_field == 'achieve': event_counts = Street.objects.all().values( 'name', 'number').order_by('-number') for achieve in achieves: new_list = [achieve.name] for street_node in event_counts: new_len = 0 street = Street.objects.get(name=street_node['name']) for community in Community.objects.filter(street=street): new_len += len( Event.objects.filter(community=community, achieve=achieve, create_time__range=(start, end))) new_list.append(new_len) # print(new_list) y_lists.append(new_list) for street_node in event_counts: x_list.append(street_node['name']) elif x_field == 'community' and y_field == 'achieve': event_counts = Community.objects.all().values( 'name', 'number').order_by('-number') for achieve in achieves: new_list = [achieve.name] for street_node in event_counts: community = Community.objects.get(name=street_node['name']) new_len = len( Event.objects.filter( Q(create_time__range=(start, end)) & Q(community=community) & Q(achieve=achieve))) new_list.append(new_len) # print(new_list) y_lists.append(new_list) for community_node in event_counts: x_list.append(community_node['name']) elif x_field == 'dispose_unit' and y_field == 'achieve': event_counts = DisposeUnit.objects.all().values( 'name', 'number').order_by('-number') for achieve in achieves: new_list = [achieve.name] limit = 0 for dispose_unit_node in event_counts: dispose_unit = DisposeUnit.objects.get( name=dispose_unit_node['name']) if limit < 30: new_len = len( Event.objects.filter( Q(create_time__range=(start, end)) & Q(dispose_unit=dispose_unit) & Q(achieve=achieve))) new_list.append(new_len) new_len = 0 else: new_len += len( Event.objects.filter( Q(create_time__range=(start, end)) & Q(dispose_unit=dispose_unit) & Q(achieve=achieve))) limit += 1 new_list.append(new_len) y_lists.append(new_list) limit = 0 for dispose_unit_node in event_counts: if limit >= 30: break x_list.append(dispose_unit_node['name']) limit += 1 x_list.append("其他") elif x_field == 'main_type' and y_field == 'achieve': event_counts = MainType.objects.all().values( 'name', 'number').order_by('-number') for achieve in achieves: new_list = [achieve.name] limit = 0 new_len = 0 for main_type_node in event_counts: main_type = MainType.objects.get(name=main_type_node['name']) for sub_type in SubType.objects.filter(main_type=main_type): new_len += len( Event.objects.filter(sub_type=sub_type, achieve=achieve, create_time__range=(start, end))) if limit < 30: limit += 1 new_list.append(new_len) new_len = 0 # print(new_list) new_list.append(new_len) y_lists.append(new_list) limit = 0 for main_type_node in event_counts: if limit >= 30: break x_list.append(main_type_node['name']) limit += 1 x_list.append('其他') elif x_field == 'sub_type' and y_field == 'achieve': event_counts = SubType.objects.all().values( 'name', 'number').order_by('-number') for achieve in achieves: new_list = [achieve.name] limit = 0 new_len = 0 for sub_type_node in event_counts: sub_type = SubType.objects.get(name=sub_type_node['name']) new_len += len( Event.objects.filter( Q(create_time__range=(start, end)) & Q(achieve=achieve) & Q(sub_type=sub_type))) if limit < 60: limit += 1 new_list.append(new_len) new_len = 0 # print(new_list) new_list.append(new_len) y_lists.append(new_list) limit = 0 for sub_type_node in event_counts: if limit >= 60: break x_list.append(sub_type_node['name']) limit += 1 x_list.append('其他') b.add_xaxis(x_list) for y_list in y_lists: b.add_yaxis(y_list[0], y_list[1:], stack="stack1", category_gap="60%") b.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) \ .set_global_opts( xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-15)), # title_opts=opts.TitleOpts(title="处理事件最多的部门"), datazoom_opts=[opts.DataZoomOpts(), opts.DataZoomOpts(type_="inside")], ) c = (b) grid = Grid() grid.add(c, grid_opts=opts.GridOpts(pos_bottom="20%")) c = grid.dump_options_with_quotes() return HttpResponse(c, content_type='application/json')
def show_visualizations(self, number=-1): """ show the charts in jupyter notebook. Args: number(int): the index of chart to be shown in jupyter notebook. If number == -1, show all the charts in jupyter notebook. Returns: page(Page()): an object of class Page in pyecharts, containing the chart(s) to be shown in jupyter notebook. """ instance = self.instance if number > instance.view_num: print( "In function show_visualizations: Error, input number greater than the view numbers." ) return Page() if self.rank_method == methods_of_ranking[3]: # diversified_ranking G = myGraph(instance.view_num) for i in range(instance.view_num): view = instance.tables[instance.views[i].table_pos].views[ instance.views[i].view_pos] G.addNode(view) G.getSim() result = G.getTopK(instance.view_num) if number != -1: begin = number - 1 end = number else: begin = 0 end = instance.view_num page = Page() for order in range(begin, end): if self.rank_method == methods_of_ranking[ 3]: # diversified_ranking view = G.nodes[result[order]] else: view = instance.tables[instance.views[order].table_pos].views[ instance.views[order].view_pos] data = {} data['order'] = order data['chartname'] = instance.table_name data['describe'] = view.table.describe data['x_name'] = view.fx.name data['y_name'] = view.fy.name data['chart'] = Chart.chart[view.chart] data['classify'] = [v[0] for v in view.table.classes] data['x_data'] = view.X data['y_data'] = view.Y data['title_top'] = 5 # 以下代码与html_handle相似 margin = str(data['title_top']) + '%' if data['chart'] == 'bar': chart = (Bar().set_series_opts(label_opts=opts.LabelOpts( is_show=False)).set_global_opts( title_opts=opts.TitleOpts(title=data['chartname'], subtitle=data['describe'], pos_left='center', pos_top=margin), xaxis_opts=opts.AxisOpts(name=data['x_name']), yaxis_opts=opts.AxisOpts( name=data['y_name'], splitline_opts=opts.SplitLineOpts(is_show=True)))) elif data['chart'] == 'pie': chart = (Pie().set_global_opts( title_opts=opts.TitleOpts(title=data['chartname'], subtitle=data['describe'], pos_left='center', pos_top=margin))) elif data['chart'] == 'line': chart = (Line().set_series_opts(label_opts=opts.LabelOpts( is_show=False)).set_global_opts( title_opts=opts.TitleOpts(title=data['chartname'], subtitle=data['describe'], pos_left='center', pos_top=margin), xaxis_opts=opts.AxisOpts(name=data['x_name']), yaxis_opts=opts.AxisOpts( name=data['y_name'], splitline_opts=opts.SplitLineOpts(is_show=True)))) elif data['chart'] == 'scatter': chart = (Scatter().set_series_opts(label_opts=opts.LabelOpts( is_show=False)).set_global_opts( title_opts=opts.TitleOpts(title=data['chartname'], subtitle=data['describe'], pos_left='center', pos_top=margin), xaxis_opts=opts.AxisOpts( type_='value', name=data['x_name'], splitline_opts=opts.SplitLineOpts(is_show=True)), yaxis_opts=opts.AxisOpts( type_='value', name=data['y_name'], splitline_opts=opts.SplitLineOpts(is_show=True)))) else: print("not valid chart") if not data["classify"]: attr = data["x_data"][0] val = data["y_data"][0] if data['chart'] == 'bar': chart.add_xaxis(attr).add_yaxis( "", val, label_opts=opts.LabelOpts(is_show=False)) elif data['chart'] == 'line': chart.add_xaxis(attr).add_yaxis( "", val, label_opts=opts.LabelOpts(is_show=False)) elif data['chart'] == 'pie': chart.add("", [list(z) for z in zip(attr, val)]) elif data['chart'] == 'scatter': if isinstance(attr[0], str): attr = [x for x in attr if x != ''] attr = list(map(float, attr)) if isinstance(val[0], str): val = [x for x in val if x != ''] val = list(map(float, val)) chart.add_xaxis(attr).add_yaxis( "", val, label_opts=opts.LabelOpts(is_show=False)) page.add(chart) else: attr = data["x_data"][0] for i in range(len(data["classify"])): val = data["y_data"][i] name = (data["classify"][i][0] if type(data["classify"][i]) == type(('a', 'b')) else data["classify"][i]) if i == 0: if data['chart'] != 'pie' and data[ 'chart'] != 'scatter': chart.add_xaxis(attr) if data['chart'] == 'bar': chart.add_yaxis( name, val, stack="stack1", label_opts=opts.LabelOpts(is_show=False)) elif data['chart'] == 'line': chart.add_yaxis( name, val, label_opts=opts.LabelOpts(is_show=False)) elif data['chart'] == 'pie': chart.add("", [list(z) for z in zip(attr, val)]) elif data['chart'] == 'scatter': attr_scatter = data["x_data"][i] if isinstance(attr_scatter[0], str): attr_scatter = [x for x in attr_scatter if x != ''] attr_scatter = list(map(float, attr_scatter)) if isinstance(val[0], str): val = [x for x in val if x != ''] val = list(map(float, val)) chart.add_xaxis(attr_scatter).add_yaxis( name, val, label_opts=opts.LabelOpts(is_show=False)) page.add(chart) return page
linestyle_opts=opts.LineStyleOpts(), itemstyle_opts=opts.ItemStyleOpts(opacity=0), color='#00FF00' # Ø10-2为绿色 ).add_xaxis(data_listx3).add_yaxis( 'Ø10-3', data_listy3, label_opts=opts.LabelOpts(is_show=False), linestyle_opts=opts.LineStyleOpts(), itemstyle_opts=opts.ItemStyleOpts(opacity=0), color='#0000FF' # Ø10-3为红色 ).set_global_opts( # 设置全局样式 title_opts=opts.TitleOpts(title='钢筋的应力应变图', pos_bottom='0', pos_right='35%'), xaxis_opts=opts.AxisOpts(type_='value', boundary_gap=False, name="拉伸应变ε,mm"), # 设置x轴类型属性为value数值类型 yaxis_opts=opts.AxisOpts( # 单轴配置项 name="应力σ,MPa", type_="value", axistick_opts=opts.AxisTickOpts(is_show=True), # 显示坐标轴刻度 splitline_opts=opts.SplitLineOpts(is_show=True) # 显示分割线 ), tooltip_opts=opts.TooltipOpts( is_show=True, trigger="axis", trigger_on="mousemove|click", axis_pointer_type="cross" # 启用十字准星指示器 ), toolbox_opts=opts.ToolboxOpts( # 工具箱,支持区域缩放和图片下载 is_show=True,
title = 'PYTHON' subtitle = '年龄分布要求' age_bar = ( Bar().add_xaxis(age_num[:-1]) # 剔除“年龄不限”类别 .add_yaxis('', age_counts[:-1]).set_series_opts( label_opts=opts.LabelOpts(is_show=False), markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_='max', name='最大值'), opts.MarkPointItem(type_='min', name='最小值') ]), ).set_global_opts( title_opts=opts.TitleOpts(title=title, subtitle=subtitle, pos_left='center'), xaxis_opts=opts.AxisOpts( name='年龄段', position='center', axislabel_opts=opts.LabelOpts(formatter="{value}岁")), yaxis_opts=opts.AxisOpts(name='职位数', ), ) # .render(title + '_' + subtitle + '.html') ) # In[4]: # 获得各经验段职位数量 experience_dist = df3['experience_required'].value_counts() exp_num = sorted(list(experience_dist.index)) last_num = exp_num.pop() exp_num = sorted([int(i) for i in exp_num]) exp_num.append(last_num) exp_counts = [int(experience_dist[str(i)]) for i in exp_num]
def visual(self, name='model_visual', path=None, gif=False): """ Arguments: name : str, train end save last image or gif file with html format name. path : str, train end save last image or gif file with html format to path; save_gif : bool, default False, if save_gif=True, train end save all image to gif; Return: a html file path. """ if path is not None: assert tf.io.gfile.exists(path), "`path` not exist." file = path + '/' + '{}.html'.format(name) else: file = '{}.html'.format(name) page = Page(interval=1, layout=Page.SimplePageLayout) plot_list = [] width_len = '750px' height_len = '450px' for metric_id, metric in enumerate(self.metrics): if not gif: line = Line(opts.InitOpts(width=width_len, height=height_len)) line = line.add_xaxis(list(range(1, self.epoch + 1))) line = line.add_yaxis( 'train', Series(self.epoch_logs[metric]).round(4).tolist(), is_smooth=True) if self.valid_fmt.format(metric) in self.epoch_logs: line = line.add_yaxis( self.valid_fmt.split('_')[0], Series(self.epoch_logs[self.valid_fmt.format( metric)]).round(4).tolist(), is_smooth=True) line = line.set_series_opts( label_opts=opts.LabelOpts(is_show=False), markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_='max', name='max_value'), opts.MarkPointItem(type_='min', name='min_value') ])) line = line.set_global_opts( title_opts=opts.TitleOpts(title=metric), xaxis_opts=opts.AxisOpts(name='Epoch', name_location='center', is_scale=True), datazoom_opts=[ opts.DataZoomOpts(range_start=0, range_end=100) ], toolbox_opts=opts.ToolboxOpts()) plot_list.append(line) else: timeline = Timeline( opts.InitOpts(width=width_len, height=height_len)).add_schema( play_interval=100, is_auto_play=True) for i in range(1, self.epoch + 1): line = Line( opts.InitOpts(width=width_len, height=height_len)) line = line.add_xaxis(list(range(1, i + 1))) line = line.add_yaxis( 'train', Series(self.epoch_logs[metric])[:i].round(4).tolist(), is_smooth=True) if self.valid_fmt.format(metric) in self.epoch_logs: line = line.add_yaxis( self.valid_fmt.split('_')[0], Series(self.epoch_logs[self.valid_fmt.format( metric)])[:i].round(4).tolist(), is_smooth=True) line = line.set_series_opts( label_opts=opts.LabelOpts(is_show=False), markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_='max', name='max_value'), opts.MarkPointItem(type_='min', name='min_value') ])) line = line.set_global_opts( title_opts=opts.TitleOpts(title=metric), xaxis_opts=opts.AxisOpts(name='Epoch', name_location='center', is_scale=True)) timeline.add(line, str(i)) plot_list.append(timeline) page.add(*plot_list).render(file) return file
def bar_base() -> Bar: # c = ( # Bar() # .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]) # .add_yaxis("商家A", [randrange(0, 100) for _ in range(6)]) # .add_yaxis("商家B", [randrange(0, 100) for _ in range(6)]) # .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题")) # ) data = [ [2320.26, 2320.26, 2287.3, 2362.94], [2300, 2291.3, 2288.26, 2308.38], [2295.35, 2346.5, 2295.35, 2345.92], [2347.22, 2358.98, 2337.35, 2363.8], [2360.75, 2382.48, 2347.89, 2383.76], [2383.43, 2385.42, 2371.23, 2391.82], [2377.41, 2419.02, 2369.57, 2421.15], [2425.92, 2428.15, 2417.58, 2440.38], [2411, 2433.13, 2403.3, 2437.42], [2432.68, 2334.48, 2427.7, 2441.73], [2430.69, 2418.53, 2394.22, 2433.89], [2416.62, 2432.4, 2414.4, 2443.03], [2441.91, 2421.56, 2418.43, 2444.8], [2420.26, 2382.91, 2373.53, 2427.07], [2383.49, 2397.18, 2370.61, 2397.94], [2378.82, 2325.95, 2309.17, 2378.82], [2322.94, 2314.16, 2308.76, 2330.88], [2320.62, 2325.82, 2315.01, 2338.78], [2313.74, 2293.34, 2289.89, 2340.71], [2297.77, 2313.22, 2292.03, 2324.63], [2322.32, 2365.59, 2308.92, 2366.16], [2364.54, 2359.51, 2330.86, 2369.65], [2332.08, 2273.4, 2259.25, 2333.54], [2274.81, 2326.31, 2270.1, 2328.14], [2333.61, 2347.18, 2321.6, 2351.44], [2340.44, 2324.29, 2304.27, 2352.02], [2326.42, 2318.61, 2314.59, 2333.67], [2314.68, 2310.59, 2296.58, 2320.96], [2309.16, 2286.6, 2264.83, 2333.29], [2282.17, 2263.97, 2253.25, 2286.33], [2255.77, 2270.28, 2253.31, 2276.22], ] c = (Kline().add_xaxis( ["2017/7/{}".format(i + 1) for i in range(31)]).add_yaxis( "kline", data, markline_opts=opts.MarkLineOpts(data=[ opts.MarkLineItem(type_="max", value_dim="close"), opts.MarkLineItem(type_="min", value_dim="close"), ], linestyle_opts=[]), ).set_global_opts( xaxis_opts=opts.AxisOpts(is_scale=True), yaxis_opts=opts.AxisOpts( is_scale=True, splitarea_opts=opts.SplitAreaOpts( is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=1)), ), title_opts=opts.TitleOpts(title="Kline-MarkLine"), )) return c
def kline_pro(kline: List[dict], fx: List[dict] = None, bi: List[dict] = None, xd: List[dict] = None, bs: List[dict] = None, title: str = "缠中说禅K线分析", t_seq: List[int] = None, width: str = "1400px", height: str = '580px') -> Grid: """绘制缠中说禅K线分析结果 :param kline: K线 :param fx: 分型识别结果 :param bi: 笔识别结果 {'dt': Timestamp('2020-11-26 00:00:00'), 'fx_mark': 'd', 'start_dt': Timestamp('2020-11-25 00:00:00'), 'end_dt': Timestamp('2020-11-27 00:00:00'), 'fx_high': 144.87, 'fx_low': 138.0, 'bi': 138.0} :param xd: 线段识别结果 :param bs: 买卖点 :param title: 图表标题 :param t_seq: 均线系统 :param width: 图表宽度 :param height: 图表高度 :return: 用Grid组合好的图表 """ # 配置项设置 # ------------------------------------------------------------------------------------------------------------------ bg_color = "#1f212d" # 背景 up_color = "#F9293E" down_color = "#00aa3b" init_opts = opts.InitOpts(bg_color=bg_color, width=width, height=height, animation_opts=opts.AnimationOpts(False)) title_opts = opts.TitleOpts(title=title, pos_top="1%", title_textstyle_opts=opts.TextStyleOpts(color=up_color, font_size=20), subtitle_textstyle_opts=opts.TextStyleOpts(color=down_color, font_size=12)) label_not_show_opts = opts.LabelOpts(is_show=False) legend_not_show_opts = opts.LegendOpts(is_show=False) red_item_style = opts.ItemStyleOpts(color=up_color) green_item_style = opts.ItemStyleOpts(color=down_color) k_style_opts = opts.ItemStyleOpts(color=up_color, color0=down_color, border_color=up_color, border_color0=down_color, opacity=0.8) legend_opts = opts.LegendOpts(is_show=True, pos_top="1%", pos_left="30%", item_width=14, item_height=8, textstyle_opts=opts.TextStyleOpts(font_size=12, color="#0e99e2")) brush_opts = opts.BrushOpts(tool_box=["rect", "polygon", "keep", "clear"], x_axis_index="all", brush_link="all", out_of_brush={"colorAlpha": 0.1}, brush_type="lineX") axis_pointer_opts = opts.AxisPointerOpts(is_show=True, link=[{"xAxisIndex": "all"}]) dz_inside = opts.DataZoomOpts(False, "inside", xaxis_index=[0, 1, 2], range_start=80, range_end=100) dz_slider = opts.DataZoomOpts(True, "slider", xaxis_index=[0, 1, 2], pos_top="96%", pos_bottom="0%", range_start=80, range_end=100) yaxis_opts = opts.AxisOpts(is_scale=True, axislabel_opts=opts.LabelOpts(color="#c7c7c7", font_size=8, position="inside")) grid0_xaxis_opts = opts.AxisOpts(type_="category", grid_index=0, axislabel_opts=label_not_show_opts, split_number=20, min_="dataMin", max_="dataMax", is_scale=True, boundary_gap=False, axisline_opts=opts.AxisLineOpts(is_on_zero=False)) tool_tip_opts = opts.TooltipOpts( trigger="axis", axis_pointer_type="cross", background_color="rgba(245, 245, 245, 0.8)", border_width=1, border_color="#ccc", position=JsCode(""" function (pos, params, el, elRect, size) { var obj = {top: 10}; obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 30; return obj; } """), textstyle_opts=opts.TextStyleOpts(color="#000"), ) # 数据预处理 # ------------------------------------------------------------------------------------------------------------------ dts = [x['dt'] for x in kline] # k_data = [[x['open'], x['close'], x['low'], x['high']] for x in kline] k_data = [opts.CandleStickItem(name=i, value=[x['open'], x['close'], x['low'], x['high']]) for i, x in enumerate(kline)] vol = [] for i, row in enumerate(kline): item_style = red_item_style if row['close'] > row['open'] else green_item_style bar = opts.BarItem(name=i, value=row['vol'], itemstyle_opts=item_style, label_opts=label_not_show_opts) vol.append(bar) close = np.array([x['close'] for x in kline], dtype=np.double) diff, dea, macd = MACD(close) macd_bar = [] for i, v in enumerate(macd.tolist()): item_style = red_item_style if v > 0 else green_item_style bar = opts.BarItem(name=i, value=round(v, 4), itemstyle_opts=item_style, label_opts=label_not_show_opts) macd_bar.append(bar) diff = diff.round(4) dea = dea.round(4) # K 线主图 # ------------------------------------------------------------------------------------------------------------------ chart_k = Kline() chart_k.add_xaxis(xaxis_data=dts) chart_k.add_yaxis(series_name="Kline", y_axis=k_data, itemstyle_opts=k_style_opts) chart_k.set_global_opts( legend_opts=legend_opts, datazoom_opts=[dz_inside, dz_slider], yaxis_opts=yaxis_opts, tooltip_opts=tool_tip_opts, axispointer_opts=axis_pointer_opts, brush_opts=brush_opts, title_opts=title_opts, xaxis_opts=grid0_xaxis_opts ) # 均线图 # ------------------------------------------------------------------------------------------------------------------ chart_ma = Line() chart_ma.add_xaxis(xaxis_data=dts) if not t_seq: t_seq = [10, 20, 60, 120, 250] ma_keys = dict() for t in t_seq: ma_keys[f"MA{t}"] = SMA(close, timeperiod=t) for i, (name, ma) in enumerate(ma_keys.items()): chart_ma.add_yaxis(series_name=name, y_axis=ma, is_smooth=True, is_selected=True, symbol_size=0, label_opts=label_not_show_opts, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1)) chart_ma.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_ma) # 缠论结果 # ------------------------------------------------------------------------------------------------------------------ if fx: fx_dts = [x['dt'] for x in fx] fx_val = [x['fx'] for x in fx] chart_fx = Scatter() chart_fx.add_xaxis(fx_dts) chart_fx.add_yaxis(series_name="FX", y_axis=fx_val, is_selected=False, symbol="circle", symbol_size=6, label_opts=label_not_show_opts, itemstyle_opts=opts.ItemStyleOpts(color="rgba(152, 147, 193, 1.0)", )) chart_fx.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_fx) if bi: bi_dts = [x['dt'] for x in bi] bi_val = [x['bi'] for x in bi] chart_bi = Line() chart_bi.add_xaxis(bi_dts) chart_bi.add_yaxis(series_name="BI", y_axis=bi_val, is_selected=True, symbol="diamond", symbol_size=10, label_opts=label_not_show_opts, itemstyle_opts=opts.ItemStyleOpts(color="rgba(184, 117, 225, 1.0)", ), linestyle_opts=opts.LineStyleOpts(width=1.5)) chart_bi.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_bi) if xd: xd_dts = [x['dt'] for x in xd] xd_val = [x['xd'] for x in xd] chart_xd = Line() chart_xd.add_xaxis(xd_dts) chart_xd.add_yaxis(series_name="XD", y_axis=xd_val, is_selected=True, symbol="triangle", symbol_size=10, itemstyle_opts=opts.ItemStyleOpts(color="rgba(37, 141, 54, 1.0)", )) chart_xd.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_xd) if bs: b_dts = [x['dt'] for x in bs if x['mark'] == 'buy'] if len(b_dts) > 0: b_val = [x['price'] for x in bs if x['mark'] == 'buy'] chart_b = Scatter() chart_b.add_xaxis(b_dts) chart_b.add_yaxis(series_name="BUY", y_axis=b_val, is_selected=False, symbol="arrow", symbol_size=8, itemstyle_opts=opts.ItemStyleOpts(color="#f31e1e", )) chart_b.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_b) s_dts = [x['dt'] for x in bs if x['mark'] == 'sell'] if len(s_dts) > 0: s_val = [x['price'] for x in bs if x['mark'] == 'sell'] chart_s = Scatter() chart_s.add_xaxis(s_dts) chart_s.add_yaxis(series_name="SELL", y_axis=s_val, is_selected=False, symbol="pin", symbol_size=12, itemstyle_opts=opts.ItemStyleOpts(color="#45b97d", )) chart_s.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_s) # 成交量图 # ------------------------------------------------------------------------------------------------------------------ chart_vol = Bar() chart_vol.add_xaxis(dts) chart_vol.add_yaxis(series_name="Volume", y_axis=vol, bar_width='60%') chart_vol.set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=1, axislabel_opts=opts.LabelOpts(is_show=True, font_size=8, color="#9b9da9"), ), yaxis_opts=yaxis_opts, legend_opts=legend_not_show_opts, ) # MACD图 # ------------------------------------------------------------------------------------------------------------------ chart_macd = Bar() chart_macd.add_xaxis(dts) chart_macd.add_yaxis(series_name="MACD", y_axis=macd_bar, bar_width='60%') chart_macd.set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", grid_index=2, axislabel_opts=opts.LabelOpts(is_show=False), ), yaxis_opts=opts.AxisOpts( grid_index=2, split_number=4, axisline_opts=opts.AxisLineOpts(is_on_zero=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), axislabel_opts=opts.LabelOpts(is_show=True, color="#c7c7c7"), ), legend_opts=opts.LegendOpts(is_show=False), ) line = Line() line.add_xaxis(dts) line.add_yaxis(series_name="DIFF", y_axis=diff, label_opts=label_not_show_opts, is_symbol_show=False, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color="#da6ee8")) line.add_yaxis(series_name="DEA", y_axis=dea, label_opts=label_not_show_opts, is_symbol_show=False, linestyle_opts=opts.LineStyleOpts(opacity=0.8, width=1.0, color="#39afe6")) chart_macd = chart_macd.overlap(line) grid0_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="12%", height="58%") grid1_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="74%", height="8%") grid2_opts = opts.GridOpts(pos_left="0%", pos_right="1%", pos_top="86%", height="10%") grid_chart = Grid(init_opts) grid_chart.add(chart_k, grid_opts=grid0_opts) grid_chart.add(chart_vol, grid_opts=grid1_opts) grid_chart.add(chart_macd, grid_opts=grid2_opts) return grid_chart
def find_value_render(query_filter, x_label, x, result, Data, query, table_path, answer): colorList = ['#f36c6c', '#e6cf4e', '#20d180', '#0093ff'] # x = ['GDP', 'Industry', 'Architecture', 'Service'] # y = [990865, 317109, 70904, 534233] # x1 = ["周一"] # y1 = [11] Y = [] # for i in range(len(y)): # if i==0: # Y.append( # opts.BarItem( # name=x[i], # value=round(y[i], 2), # label_opts=opts.LabelOpts(position="insideTop"), # itemstyle_opts={ # "normal": { # "color": colorList[0], # "barBorderRadius": [30, 30, 30, 30], # } # } # )) # else: # Y.append( # opts.BarItem( # name=x[i], # value=round(y[i], 2), # label_opts=opts.LabelOpts(position="insideTop"), # itemstyle_opts={ # "normal": { # "color": "blue", # "barBorderRadius": [30, 30, 30, 30], # } # } # )) bar1 = Bar() bar1.add_xaxis(x) bar1.add_yaxis(result[0][0], y_axis=result[0][1], label_opts=opts.LabelOpts(position="insideTop")) bar1.set_global_opts( yaxis_opts=opts.AxisOpts(is_show=False), xaxis_opts=opts.AxisOpts( axisline_opts=opts.AxisLineOpts(is_show=False), axispointer_opts=opts.AxisPointerOpts(is_show=False), axistick_opts=opts.AxisTickOpts(is_show=False)), title_opts=opts.TitleOpts(subtitle="When the search condition is " + query_filter, pos_left='center'), graphic_opts=[ opts.GraphicText( graphic_item=opts.GraphicItem( left="center", top="bottom", z=100, ), graphic_textstyle_opts=opts.GraphicTextStyleOpts( # 可以通过jsCode添加js代码,也可以直接用字符串 text=[ '\n' + "Q:" + ' ' + query + '\n' + "\n" + 'A:' + ' ' + answer ], font="14px Microsoft YaHei", graphic_basicstyle_opts=opts.GraphicBasicStyleOpts( fill="#333"))) ]) bar2 = Bar() bar2.add_xaxis(x) for i in range(len(result)): bar2.add_yaxis(result[i][0], y_axis=result[i][1]) bar2.set_global_opts( yaxis_opts=opts.AxisOpts(is_show=False), xaxis_opts=opts.AxisOpts( axisline_opts=opts.AxisLineOpts(is_show=False), axispointer_opts=opts.AxisPointerOpts(is_show=False), axistick_opts=opts.AxisTickOpts(is_show=False)), graphic_opts=[ opts.GraphicText( graphic_item=opts.GraphicItem( left="center", top="bottom", z=100, ), graphic_textstyle_opts=opts.GraphicTextStyleOpts( # 可以通过jsCode添加js代码,也可以直接用字符串 text=[ '\n' + "\n" + "Q:" + ' ' + query + '\n' + "\n" + 'A:' + ' ' + answer ], font="16px Microsoft YaHei", graphic_basicstyle_opts=opts.GraphicBasicStyleOpts( fill="#333"))) ]) Label = [] data = [] for i in range(len(Data)): Label.append(str(Data[i][0])) data.append(Data[i][1]) data = list(map(list, zip(*data))) parallel = Parallel() parallel_axis = [] for i in range(len(Label)): parallel_axis.append({"dim": i, "name": Label[i]}) parallel.add_schema(schema=parallel_axis) parallel.add("", data, is_smooth=True) parallel.set_global_opts(graphic_opts=[ opts.GraphicText( graphic_item=opts.GraphicItem( left="center", top="bottom", z=100, ), graphic_textstyle_opts=opts.GraphicTextStyleOpts( # 可以通过jsCode添加js代码,也可以直接用字符串 text=['\n' + "Q:" + ' ' + query + '\n' + 'A:' + ' ' + answer], font="14px Microsoft YaHei", graphic_basicstyle_opts=opts.GraphicBasicStyleOpts( fill="#333"))) ]) grid0 = Grid(init_opts=opts.InitOpts( width="100%", height="100%", renderer=globals.RenderType.SVG, )) grid0.add(bar1, grid_opts={'left': '20%', 'bottom': '34%'}) option0 = grid0.dump_options_with_quotes() option0 = json.loads(option0) grid = Grid(init_opts=opts.InitOpts( width="100%", height="100%", renderer=globals.RenderType.SVG, )) grid.add(bar2, grid_opts={'left': '15%', 'bottom': '50%'}) option1 = grid.dump_options_with_quotes() option1 = json.loads(option1) grid1 = Grid(init_opts=opts.InitOpts( width="100%", height="100%", renderer=globals.RenderType.SVG, )) grid1.add(parallel, grid_opts={'left': '30%', 'bottom': '34%'}) option2 = grid1.dump_options_with_quotes() option2 = json.loads(option2) option = {"option": [option1, option2], "query": query} return option
def get_year_chart(year: str): map_data = [ [[x["name"], x["value"]] for x in d["data"]] for d in MapData if d["time"] == year ][0] min_data, max_data = (minNum, maxNum) data_mark: List = [] i = 0 for x in time_list: if x == year: data_mark.append(total_num[i]) else: data_mark.append("") i = i + 1 map_chart = ( Map() .add( series_name="", data_pair=map_data, zoom=1, center=[119.5, 34.5], is_map_symbol_show=False, itemstyle_opts={ "normal": {"areaColor": "#323c48", "borderColor": "#404a59"}, "emphasis": { "label": {"show": Timeline}, "areaColor": "rgba(255,255,255, 0.5)", }, }, ) .set_global_opts( title_opts=opts.TitleOpts( title="" + str(year) + "全国各省份NCP实时动态(数据来源:丁香园; 数据仓库:BlankerL/DXY-2019-nCoV-Data)", subtitle="", pos_left="center", pos_top="top", title_textstyle_opts=opts.TextStyleOpts( font_size=25, color="rgba(255,255,255, 0.9)" ), ), tooltip_opts=opts.TooltipOpts( is_show=True, formatter=JsCode( """function(params) { if ('value' in params.data) { return params.data.value[2] + ': ' + params.data.value[0]; } }""" ), ), visualmap_opts=opts.VisualMapOpts( is_calculable=True, dimension=0, pos_left="30", pos_top="center", range_text=["High", "Low"], range_color=["lightskyblue", "yellow", "orangered"], textstyle_opts=opts.TextStyleOpts(color="#ddd"), min_=min_data, max_=max_data, ), ) ) line_chart = ( Line() .add_xaxis(time_list) .add_yaxis("", total_num) .add_yaxis( "", data_mark, markpoint_opts=opts.MarkPointOpts( data=[opts.MarkPointItem(type_="max")]), ) .set_series_opts(label_opts=opts.LabelOpts(is_show=False)) .set_global_opts( title_opts=opts.TitleOpts( title="全国各省份NCP实时动态(单位: 百人)", pos_left="72%", pos_top="5%" ) ) ) bar_x_data = [x[0] for x in map_data] bar_y_data = [{"name": x[0], "value": x[1][0]} for x in map_data] bar = ( Bar() .add_xaxis(xaxis_data=bar_x_data) .add_yaxis( series_name="", yaxis_data=bar_y_data, label_opts=opts.LabelOpts( is_show=True, position="right", formatter="{b} : {c}" ), ) .reversal_axis() .set_global_opts( xaxis_opts=opts.AxisOpts( max_=40000, axislabel_opts=opts.LabelOpts(is_show=False) ), yaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(is_show=False)), tooltip_opts=opts.TooltipOpts(is_show=False), visualmap_opts=opts.VisualMapOpts( is_calculable=True, dimension=0, pos_left="10", pos_top="top", range_text=["High", "Low"], range_color=["lightskyblue", "yellow", "orangered"], textstyle_opts=opts.TextStyleOpts(color="#ddd"), min_=min_data, max_=max_data, ), ) ) pie_data = [[x[0], x[1][0]] for x in map_data] pie = ( Pie() .add( series_name="", data_pair=pie_data, radius=["15%", "35%"], center=["80%", "82%"], itemstyle_opts=opts.ItemStyleOpts( border_width=1, border_color="rgba(0,0,0,0.5)" ), ) .set_global_opts( tooltip_opts=opts.TooltipOpts(is_show=True, formatter="{b} {d}%"), legend_opts=opts.LegendOpts(is_show=False), ) ) grid_chart = ( Grid() .add( bar, grid_opts=opts.GridOpts( pos_left="10", pos_right="45%", pos_top="50%", pos_bottom="5" ), ) .add( line_chart, grid_opts=opts.GridOpts( pos_left="65%", pos_right="80", pos_top="10%", pos_bottom="50%" ), ) .add(pie, grid_opts=opts.GridOpts(pos_left="45%", pos_top="60%")) .add(map_chart, grid_opts=opts.GridOpts()) ) return grid_chart
def generate_price_bar_html(rows, title): xx1 = [] xx2 = [] yy1 = [] yy2 = [] count = 0 for row in rows: bond_code = row[0] bond_code = trade_utils.rebuild_bond_code(bond_code) count += 1 if count <= 20: xx1.append(row[1].replace('转债', '')) yy1.append({ 'value': row[2], 'bond_code': bond_code, 'rise': row[3], 'premium': row[4] }) else: xx2.insert(0, row[1].replace('转债', '')) yy2.insert( 0, { 'value': round(-float(row[2]) + 0, 2), 'bond_code': bond_code, 'rise': row[3], 'premium': row[4] }) max_value = 0 size = len(yy1) for i in range(size): if yy1[i]['value'] + abs(yy2[i]['value']) > max_value: max_value = yy1[i]['value'] + abs(yy2[i]['value']) max_value = round(max_value * 0.7, 2) + 1 chart_id = str(abs(hash(title))) bar = Bar(init_opts=opts.InitOpts(height='700px', width='1424px', theme=ThemeType.SHINE, chart_id=chart_id)) add_popwin_js_code(bar, chart_id) # 底部x轴 bar.add_xaxis(xx1) # 顶部x轴 bar.extend_axis( xaxis_data=xx2, xaxis=opts.AxisOpts(type_="category", position='top', axislabel_opts=opts.LabelOpts(rotate=-60, )), ) # 右侧y轴 bar.extend_axis(yaxis=opts.AxisOpts( type_="value", position="right", name='可转债价格(元)', name_gap=45, name_location='middle', min_=-max_value, is_scale=True, axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(is_show=True, )), # axislabel_opts=opts.LabelOpts(formatter="{value}"), axislabel_opts=opts.LabelOpts( formatter=JsCode("function(x){return (x + '元').substring(1);}")), )) # 添加高价格的柱状图 bar.add_yaxis( "高价格", yy1, bar_width=25, category_gap='1%', gap='1%', label_opts=opts.LabelOpts( is_show=True, position="top", formatter=JsCode("function(x){return x.data['value']+'元';}")), ) # 添加低价格的柱状图 bar.add_yaxis( "低价格", yy2, bar_width=25, yaxis_index=1, label_opts=opts.LabelOpts( is_show=True, position="bottom", formatter=JsCode( "function(x){return (x.data['value'] + '元').substring(1);}")), ) # bar.reversal_axis() bar.set_series_opts( # itemstyle_opts=opts.ItemStyleOpts( # color=JsCode( # "function(x){return x.data['value']>0?'#c23531':'#1d953f'}" # ) # ) ) bar.set_global_opts( title_opts=opts.TitleOpts( title="=========" + title + "=========", pos_left='center', pos_top='-1px', ), tooltip_opts=opts.TooltipOpts( is_show=True, formatter=JsCode( "function (params){return '名 称: ' + params.name + '<br/>' + '涨 跌: ' + params.data['rise'] + '%<br/>' + '溢价率: ' + params.data['premium']}" )), legend_opts=opts.LegendOpts(is_show=False), xaxis_opts=opts.AxisOpts( # data=None, # type_='category', # name_gap=0, # name_rotate=90, axislabel_opts=opts.LabelOpts(rotate=-60, ), is_scale=True, name_location='middle', splitline_opts=opts.SplitLineOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_on_zero=True, # symbol=['none', 'arrow'] )), yaxis_opts=opts.AxisOpts( type_='value', name='可转债价格(元)', # name_rotate=90, name_gap=35, name_location='middle', # min_=0, max_=max_value, is_scale=True, axislabel_opts=opts.LabelOpts(formatter='{value}元'), splitline_opts=opts.SplitLineOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_on_zero=False, # symbol=['none', 'arrow'] )), ) bar_html = bar.render_embed('template.html', html_utils.env) return bar_html
week_name_list = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] high_temperature = [11, 11, 15, 13, 12, 13, 10] low_temperature = [1, -2, 2, 5, 3, 2, 0] (Line(init_opts=opts.InitOpts(width="1600px", height="800px")).add_xaxis( xaxis_data=week_name_list).add_yaxis( series_name="最高气温", y_axis=high_temperature, markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_="max", name="最大值"), opts.MarkPointItem(type_="min", name="最小值"), ]), markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_="average", name="平均值")]), ).add_yaxis( series_name="最低气温", y_axis=low_temperature, markpoint_opts=opts.MarkPointOpts( data=[opts.MarkPointItem(value=-2, name="周最低", x=1, y=-1.5)]), markline_opts=opts.MarkLineOpts(data=[ opts.MarkLineItem(type_="average", name="平均值"), opts.MarkLineItem(symbol="none", x="90%", y="max"), opts.MarkLineItem(symbol="circle", type_="max", name="最高点"), ]), ).set_global_opts( title_opts=opts.TitleOpts(title="城市气温变化图表", subtitle="数据来源中国天气网"), tooltip_opts=opts.TooltipOpts(trigger="axis"), toolbox_opts=opts.ToolboxOpts(is_show=True), xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False), ).render("temperature_change_line_chart.html"))
from pyecharts.charts import Bar # 柱状图对象 from pyecharts import options # 配置对象 from pyecharts.globals import ThemeType # 创建柱状图对象 (Bar({'theme': ThemeType.DARK}) # 添加横坐标 .add_xaxis(["冰箱", "洗衣机", "彩电", "空调", "电脑", "电饭煲"]) # 添加纵坐标(数据)可以添加多个 .add_yaxis("格力", [100, 200, 250, 150, 50, 300], stack="strack").add_yaxis("小米", [200, 100, 50, 150, 240, 180], stack="strack") # 创建标题对象 .set_global_opts( title_opts=options.TitleOpts(title="家电销售情况"), # visualmap_opts=options.VisualMapOpts(max_=200), # 设置阈值 datazoom_opts=[options.DataZoomOpts()], # 拉的进度条 brush_opts=options.BrushOpts(), # 工具栏 yaxis_opts=options.AxisOpts(name="y轴名字"), xaxis_opts=options.AxisOpts(name="x轴名字"), ).render("家电柱状图.html"))
opacity=1), ).set_global_opts( title_opts=opts.TitleOpts( title="OCTOBER 2015", pos_bottom="5%", pos_left="center", title_textstyle_opts=opts.TextStyleOpts(color="#fff", font_size=16), ), xaxis_opts=opts.AxisOpts( type_="category", boundary_gap=False, axislabel_opts=opts.LabelOpts(margin=30, color="#ffffff63"), axisline_opts=opts.AxisLineOpts(is_show=False), axistick_opts=opts.AxisTickOpts( is_show=True, length=25, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"), ), splitline_opts=opts.SplitLineOpts( is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")), ), yaxis_opts=opts.AxisOpts( type_="value", position="right", axislabel_opts=opts.LabelOpts(margin=20, color="#ffffff63"), axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(width=2, color="#fff")), axistick_opts=opts.AxisTickOpts( is_show=True, length=15,
"2015-4", "2015-5", "2015-6", "2015-7", "2015-8", "2015-9", "2015-10", "2015-11", "2015-12", ], xaxis=opts.AxisOpts( type_="category", axistick_opts=opts.AxisTickOpts(is_align_with_label=True), axisline_opts=opts.AxisLineOpts( is_on_zero=False, linestyle_opts=opts.LineStyleOpts(color="#6e9ef1")), axispointer_opts=opts.AxisPointerOpts( is_show=True, label=opts.LabelOpts(formatter=produce_js_func(js_formatter)), ), ), ).add_yaxis( series_name="2015 降水量", is_smooth=True, symbol="emptyCircle", is_symbol_show=False, # xaxis_index=1, color="#d14a61", y_axis=[ 2.6, 5.9, 9.0, 26.4, 28.7, 70.7, 175.6, 182.2, 48.7, 18.8, 6.0, 2.3 ],
[57.1, 78254, "Milk Tea"], [74.4, 41032, "Cheese Cocoa"], [50.1, 12755, "Cheese Brownie"], [89.7, 20145, "Matcha Cocoa"], [68.1, 79146, "Tea"], [19.6, 91852, "Orange Juice"], [10.6, 101852, "Lemon Juice"], [32.7, 20112, "Walnut Brownie"], ]).add_yaxis( series_name="", yaxis_data=[], encode={ "x": "amount", "y": "product" }, label_opts=opts.LabelOpts(is_show=False), ).set_global_opts( title_opts=opts.TitleOpts(title="Dataset normal bar example"), xaxis_opts=opts.AxisOpts(name="amount"), yaxis_opts=opts.AxisOpts(type_="category"), visualmap_opts=opts.VisualMapOpts( orient="horizontal", pos_left="center", min_=10, max_=100, range_text=["High Score", "Low Score"], dimension=0, range_color=["#D7DA8B", "#E15457"], ), ).render("dataset_bar_1.html"))
def citedLine(x_data, y_data): background_color_js = ( "new echarts.graphic.LinearGradient(0, 0, 0, 1, " "[{offset: 0, color: '#c86589'}, {offset: 1, color: '#06a7ff'}], false)" ) area_color_js = ( "new echarts.graphic.LinearGradient(0, 0, 0, 1, " "[{offset: 0, color: '#eb64fb'}, {offset: 1, color: '#3fbbff0d'}], false)" ) cl = (Line(init_opts=opts.InitOpts( bg_color=JsCode(background_color_js), width="1350px", height="750px")).add_xaxis(xaxis_data=x_data).add_yaxis( series_name="cites", y_axis=y_data, is_smooth=True, is_symbol_show=True, symbol="circle", symbol_size=6, linestyle_opts=opts.LineStyleOpts(color="#fff"), label_opts=opts.LabelOpts(is_show=True, position="top", color="white"), itemstyle_opts=opts.ItemStyleOpts(color="red", border_color="#fff", border_width=3), tooltip_opts=opts.TooltipOpts(is_show=False), areastyle_opts=opts.AreaStyleOpts(color=JsCode(area_color_js), opacity=1), ).set_global_opts( title_opts=opts.TitleOpts( title="Cites per Years", pos_bottom="92%", pos_left="8%", title_textstyle_opts=opts.TextStyleOpts(color="#fff", font_size=16), ), xaxis_opts=opts.AxisOpts( type_="category", boundary_gap=False, axislabel_opts=opts.LabelOpts(margin=30, color="#ffffff63"), axisline_opts=opts.AxisLineOpts(is_show=False), axistick_opts=opts.AxisTickOpts( is_show=True, length=25, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"), ), splitline_opts=opts.SplitLineOpts( is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")), ), yaxis_opts=opts.AxisOpts( type_="value", position="right", axislabel_opts=opts.LabelOpts(margin=20, color="#ffffff63"), axisline_opts=opts.AxisLineOpts( linestyle_opts=opts.LineStyleOpts(width=2, color="#fff")), axistick_opts=opts.AxisTickOpts( is_show=True, length=15, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f"), ), splitline_opts=opts.SplitLineOpts( is_show=True, linestyle_opts=opts.LineStyleOpts(color="#ffffff1f")), ), legend_opts=opts.LegendOpts(is_show=False), )) return cl
#if count == 10: # break book.close() from pyecharts import options as opts from pyecharts.charts import Bar #按从大到小的顺序显示红包发放榜 slist = list(sdict.items()) slist.sort(key=lambda x: x[1], reverse=True) sbar = Bar() sbar.add_xaxis([x[0] for x in slist]) sbar.add_yaxis( "交大校友交流学习群" + _date[:4] + "年" + _date[4:6] + "月" + _date[6:] + "日红包爱心榜", [x[1] for x in slist]) sbar.set_global_opts(xaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(interval=0, rotate=30))) sbar.render(_send) #按从小到大的顺序显示红包收益榜 plist = list(pdict.items()) plist.sort(key=lambda x: x[1], reverse=False) pbar = Bar() pbar.add_xaxis([x[0] for x in plist]) pbar.add_yaxis( "交大校友交流学习群" + _date[:4] + "年" + _date[4:6] + "月" + _date[6:] + "日红包福利榜", [x[1] for x in plist]) pbar.set_global_opts(xaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(interval=0, rotate=45))) pbar.render(_play)
def analyse_data(): client = pymongo.MongoClient("mongodb://localhost:27017/") db = client['testcomment'] col = db[collection_name] result = col.find({}, {'_id': 0, '评论日期': 1, "评论": 1, "追加评论": 1}) comment_list = [] date_list = [] date_dic = {} for date in result: # 把日期和评论字数放入列表中 date_list.append(date['评论日期']) comment_list.append(len(date['评论'])) if len(date['追加评论']) != 0: comment_list.append(len(date['追加评论'])) for date in date_list: # 统计日销量 if date in date_dic: date_dic[date] += 1 else: date_dic[date] = 1 # date_list = list(date_dic) data_dic = {} arr = np.array(list(date_dic)) # 给日期排序 date_list = arr[np.argsort( [datetime.strptime(i, '%m.%d') for i in list(date_dic)])].tolist() for i in date_list: data_dic[i] = date_dic[i] # s = pd.Series(data_dic) # series表示一维数组 # comment_list.sort() word_num_dic = { '0-10': 0, '11-20': 0, '21-30': 0, '31-40': 0, '41-50': 0, '51-60': 0, '61-70': 0, '71-80': 0, '91-100': 0, '101-110': 0, '111-120': 0, '121-130': 0, '131-140': 0, '141-150': 0, '151-160': 0, '161-170': 0, '171-180': 0, '181-190': 0, '191-200': 0, '201-300': 0 } for i in word_num_dic: # 统计字数 for j in comment_list: if j >= int(i.split('-')[0]) and j <= int(i.split('-')[-1]): word_num_dic[i] += 1 # print(ndic) bar1 = ( # 生成柱状图 Bar().add_xaxis(list(data_dic.keys())).add_yaxis( '商品', list(data_dic.values())).set_global_opts( # 设置全局参数 title_opts=opts.TitleOpts(title='商品日销量'), yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts( is_show=True)), # 添加纵坐标标线 datazoom_opts=[ opts.DataZoomOpts(range_start=10, range_end=80, is_zoom_lock=False) ] # 添加滑动条 )) bar1.chart_id = '6f180e81787a48539de004c1eb847c1e' bar2 = ( # 生成柱状图 Bar({ 'theme': ThemeType.MACARONS }).add_xaxis(list(word_num_dic.keys())).add_yaxis( '商品', list(word_num_dic.values())).set_global_opts( # 设置全局参数 title_opts=opts.TitleOpts(title='字数统计'), yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts( is_show=True)), datazoom_opts=[ opts.DataZoomOpts(range_start=10, range_end=80, is_zoom_lock=False) ])) bar2.chart_id = '9a412341322b4d92bba49e3fd932a7f0' pie1 = ( # 生成柱状图 Pie().add(series_name='用户身份', data_pair=[('超级会员', vip_num), ('普通用户', comment_num - vip_num) ]).set_global_opts( # 设置全局参数 title_opts=opts.TitleOpts(title='超级会员比例'), )) pie1.chart_id = '7ed5d413532646909f127fd36f584081' pie2 = ( # 生成柱状图 Pie(init_opts=opts.InitOpts(theme=ThemeType.WESTEROS)).add( series_name='有无图片', data_pair=[('有图评价', img_num), ('无图评价', comment_num - img_num) ]).set_global_opts( # 设置全局参数 title_opts=opts.TitleOpts(title='有图评价比例'), )) pie2.chart_id = 'aa3f038854e144dbaa6e9892d4ca31fc' pie3 = ( # 生成柱状图 Pie(init_opts=opts.InitOpts(theme=ThemeType.INFOGRAPHIC)).add( series_name='是否追加', data_pair=[('追加评价', append_num), ('普通评价', comment_num - append_num) ]).set_global_opts( # 设置全局参数 title_opts=opts.TitleOpts(title='追加评价比例'), )) pie3.chart_id = '235863de6fe74a2aa9273e30ed4a7f66' page = Page(page_title='评论分析报告') page.add(bar1, bar2, pie1, pie2, pie3) page.render() Page.save_resize_html(cfg_file=r'chart_config.json') with open('resize_render.html', 'r+', encoding='utf-8') as f: f.seek(573) html = f.read() f.seek(573) f.write(' <h1>评价分析结果:</h1>\n <p>' + content + '</p>\n ') f.write(html) print( r'已完成分析 请打开E:\Python\learnPython\testspider\FinalProject\resize_render.html查看分析结果' )