def bszone(data): return opts.MarkAreaItem( x=(data["begin"].strftime("%Y-%m-%d"), data["end"].strftime("%Y-%m-%d")), itemstyle_opts=opts.ItemStyleOpts( color="#ec0000" if data["earnings_v"] > 0 else "#00da3c", opacity=0.1), )
def line_with_mark_area(): line = Line( init_opts=opts.InitOpts(theme='light', width='1000px', height='600px')) line.add_xaxis(x_data) line.add_yaxis('', y_data) line.set_series_opts(markarea_opts=opts.MarkAreaOpts( data=[opts.MarkAreaItem(name="黄金周", x=("2020/10/1", "2020/10/8"))])) return line
def line_with_mark_area(): line = Line(init_opts=opts.InitOpts(theme='essos', width='1600px', height='450px')) line.add_xaxis(x_data) line.add_yaxis('百天情感趋势图', y_data) # 设置标记区域 line.set_series_opts( markarea_opts=opts.MarkAreaOpts( data=[ opts.MarkAreaItem(name="情绪低落期", x=("1.20", "2.8")) ] ) ) return line
def bs(data): if data["bcount"] > 0: bspoints.append( opts.MarkPointItem( name="B", coord=[data.name.strftime("%Y-%m-%d"), data["bprice"]], symbol_size=20, value=str(round(data["signal"], 2)), itemstyle_opts=opts.ItemStyleOpts( color="#ec0000", color0="#ec0000", area_color="#ec0000", ), )) if data["scount"] > 0: bspoints.append( opts.MarkPointItem( name="S", coord=[data.name.strftime("%Y-%m-%d"), data["sprice"]], symbol_size=20, value=str(round(data["signal"], 2)), itemstyle_opts=opts.ItemStyleOpts(color="#00da3c"), )) global area if data["position"] > 0: if area == None: area = {} area["assets"] = data["assets"] area["date"] = data.name.strftime("%Y-%m-%d") else: if area is not None: shouyi = data["assets"] - area["assets"] shouyiv = shouyi / area["assets"] print(shouyi) bsArea.append( opts.MarkAreaItem( '收益:{:.2f} 收益率:{:.2f}'.format(shouyi, shouyiv), x=(area["date"], data.name.strftime("%Y-%m-%d")), itemstyle_opts=opts.ItemStyleOpts( color="#ec0000" if shouyi > 0 else "#00da3c", opacity=0.1), )) area = None
def kline_pro(kline: List[dict], fx: List[dict] = None, xd=None, bs: List[dict] = None, title: str = "缠中说禅K线分析", width: str = "1400px", height: str = '580px') -> Grid: """绘制缠中说禅K线分析结果 :param kline: K线 :param fx: 分型识别结果 :param bi: 笔识别结果 :param xd: 线段识别结果 :param zs: 中枢 :param bs: 买卖点 :param title: 图表标题 :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" }]) range_start = int(100 - 216 / len(kline) * 100) dz_inside = opts.DataZoomOpts(False, "inside", xaxis_index=[0, 1, 2], range_start=range_start, range_end=100) dz_slider = opts.DataZoomOpts(True, "slider", xaxis_index=[0, 1, 2], pos_top="96%", pos_bottom="0%", range_start=range_start, 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.get('dt', x['date']) for x in kline] try: dts = [x['date'] for x in kline] except: 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['volume'], 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) ma5 = SMA(close, timeperiod=5) ma34 = SMA(close, timeperiod=34) ma55 = SMA(close, timeperiod=55) ma233 = SMA(close, timeperiod=233) 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) if xd: index = 0 zs_colors = [ "yellow", "white", '#f034c1', "#7944b7", "#468b58", "#c17f2f", "#9EA0A1" ] data = [] temp_xd = xd while temp_xd: zs_color = zs_colors[index % len(zs_colors)] data = data + [ opts.MarkAreaItem( name='XD{}'.format(index), x=(x['xd_list'][0]['date'], x['xd_list'][-1]['date']), y=(x['ZG']['value'], x['ZD']['value']), label_opts=opts.LabelOpts(color=zs_color), itemstyle_opts=opts.ItemStyleOpts( color=zs_color, opacity=0.2, )) for x in temp_xd.zs_list ] temp_xd = temp_xd.next index = index + 1 chart_k.set_series_opts( markarea_opts=opts.MarkAreaOpts(is_silent=True, data=data)) # 均线图 # ------------------------------------------------------------------------------------------------------------------ chart_ma = Line() chart_ma.add_xaxis(xaxis_data=dts) ma_keys = {"MA5": ma5, "MA34": ma34, "MA55": ma55, "MA233": ma233} ma_colors = ["#39afe6", "#da6ee8", "#A02128", "#00940b"] for i, (name, ma) in enumerate(ma_keys.items()): chart_ma.add_yaxis(series_name=name, y_axis=ma, is_smooth=True, is_selected=False, symbol_size=0, label_opts=label_not_show_opts, linestyle_opts=opts.LineStyleOpts( opacity=0.8, width=1.0, color=ma_colors[i])) 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: try: fx_dts = [x['date'] for x in fx] except: fx_dts = [x['dt'] for x in fx] fx_val = [x['value'] 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 xd: index = 0 xd_colors = zs_colors while xd: xd_dts = [x['date'] for x in xd] xd_val = [x['value'] for x in xd] chart_xd = Line() chart_xd.add_xaxis(xd_dts) xd_color = xd_colors[index % len(xd_colors)] chart_xd.add_yaxis( series_name="XD{}".format(index), y_axis=xd_val, is_selected=True, symbol="triangle", symbol_size=10, linestyle_opts=opts.LineStyleOpts(color=xd_color, width=index + 1, type_="solid"), itemstyle_opts=opts.ItemStyleOpts(color=xd_color)) chart_xd.set_global_opts(xaxis_opts=grid0_xaxis_opts, legend_opts=legend_not_show_opts) chart_k = chart_k.overlap(chart_xd) xd = xd.next index = index + 1 if bs: b_dts = [x['date'] for x in bs if x['bs'] == 'buy'] if len(b_dts) > 0: b_val = [x['value'] for x in bs if x['bs'] == '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['date'] for x in bs if x['bs'] == 'sell'] if len(s_dts) > 0: s_val = [x['value'] for x in bs if x['bs'] == '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
pieces=[ { "lte": 6, "color": "green" }, { "gt": 6, "lte": 8, "color": "red" }, { "gt": 8, "lte": 14, "color": "green" }, { "gt": 14, "lte": 17, "color": "red" }, { "gt": 17, "color": "green" }, ], ), ).set_series_opts(markarea_opts=opts.MarkAreaOpts(data=[ opts.MarkAreaItem(name="早高峰", x=("07:30", "10:00")), opts.MarkAreaItem(name="晚高峰", x=("17:30", "21:15")), ])).render("distribution_of_electricity.html"))
def positionsitem(data, begin="bdate", end="sdate", value="assetsv"): return opts.MarkAreaItem( x=(data[begin], data[end]), itemstyle_opts=opts.ItemStyleOpts( color="#ec0000" if data[value] > 0 else "#00da3c", opacity=0.1), )
def draw_chart(df, extend_field, save_path="", trade_list=None, point_list=None, area_list=None, kline_title="买卖点K线图", is_smooth=True, is_connect_nones=False): datetime_array = df.datetime.tolist() volume_array = df.volume.tolist() # open close low high kline_data = df[["open", "close", "low", "high"]].values.tolist() # 绘制买卖点 _point_list = [] # 绘制标志点 if point_list is not None and len(point_list) > 1: for point in point_list: if type(point["datetime"]) == str: point_datetime = point["datetime"] else: point_datetime = point["datetime"].strftime( "%Y-%m-%d %H:%M:%S.%f") point_name = point.get("name", "") _point_list.append( opts.MarkPointItem( name=point_name, coord=[point_datetime, point["y"]], value=point_name if point_name else point["y"], itemstyle_opts=opts.ItemStyleOpts( color=point.get("color", "#ef232a")))) else: if trade_list is not None and len(trade_list) > 1: for trade in trade_list: # 开多 if type(trade[0]) == str: trade_datetime = trade[0] else: trade_datetime = trade[0].strftime( "%Y-%m-%d %H:%M:%S.%f") if trade_datetime < datetime_array[0]: continue if trade[1] == "多" and trade[4] == "开": _point_list.append( opts.MarkPointItem( name="开多", coord=[trade_datetime, trade[6]], value="开多", itemstyle_opts=opts.ItemStyleOpts( color="#ef232a"))) # 开空 elif trade[1] == "空" and trade[4] == "开": _point_list.append( opts.MarkPointItem( name="开空", coord=[trade_datetime, trade[6]], value="开空", itemstyle_opts=opts.ItemStyleOpts( color="#ef232a"))) # 平多 elif trade[1] == "多" and (trade[4] == "平" or trade[4] == "平今" or trade[4] == "平昨"): _point_list.append( opts.MarkPointItem( name="平空", coord=[trade_datetime, trade[6]], value="平空", itemstyle_opts=opts.ItemStyleOpts( color="#14b143"))) # 平空 elif trade[1] == "空" and (trade[4] == "平" or trade[4] == "平今" or trade[4] == "平昨"): _point_list.append( opts.MarkPointItem( name="平多", coord=[trade_datetime, trade[6]], value="平多", itemstyle_opts=opts.ItemStyleOpts( color="#14b143"))) # 绘制矩形 _area_list = [] if area_list is not None and len(area_list) > 1: for item in area_list: _area_list.append( opts.MarkAreaItem( x=item["x"], y=item["y"], itemstyle_opts=opts.ItemStyleOpts( color="transparent", border_color=item.get("border_color", "#4D0099"), border_width=3, border_type="dashed"), )) kline = (Kline().add_xaxis(xaxis_data=datetime_array).add_yaxis( series_name="Kline", y_axis=kline_data, itemstyle_opts=opts.ItemStyleOpts( color="#ef232a", color0="#14b143", border_color="#ef232a", border_color0="#14b143", ), markpoint_opts=opts.MarkPointOpts(data=_point_list), ).set_series_opts(markarea_opts=opts.MarkAreaOpts( data=_area_list, )).set_global_opts( title_opts=opts.TitleOpts(title=kline_title, pos_left="2%", pos_top="1%"), legend_opts=opts.LegendOpts(is_show=True, pos_top=10, pos_left="center"), datazoom_opts=[ opts.DataZoomOpts( is_show=False, type_="inside", xaxis_index=[0, 1], range_start=0, range_end=100, ), opts.DataZoomOpts( is_show=True, xaxis_index=[0, 1], type_="slider", pos_top="88%", range_start=0, range_end=100, ), ], yaxis_opts=opts.AxisOpts( is_scale=True, splitline_opts=opts.SplitLineOpts(is_show=True)), tooltip_opts=opts.TooltipOpts( trigger="axis", axis_pointer_type="cross", background_color="rgba(245, 245, 245, 0.8)", border_width=1, border_color="#ccc", textstyle_opts=opts.TextStyleOpts(color="#000"), ), visualmap_opts=opts.VisualMapOpts( is_show=False, dimension=2, series_index=5, is_piecewise=True, pieces=[ { "value": 1, "color": "#00da3c" }, { "value": -1, "color": "#ec0000" }, ], ), axispointer_opts=opts.AxisPointerOpts( is_show=True, link=[{ "xAxisIndex": "all" }], label=opts.LabelOpts(background_color="#777"), ), )) bar = (Bar().add_xaxis(xaxis_data=datetime_array).add_yaxis( series_name="Volume", y_axis=volume_array, xaxis_index=1, yaxis_index=1, label_opts=opts.LabelOpts(is_show=False), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_="category", is_scale=True, grid_index=1, boundary_gap=False, 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=False), split_number=20, min_="dataMin", max_="dataMax", ), yaxis_opts=opts.AxisOpts( grid_index=1, is_scale=True, split_number=2, axislabel_opts=opts.LabelOpts(is_show=False), axisline_opts=opts.AxisLineOpts(is_show=False), axistick_opts=opts.AxisTickOpts(is_show=False), splitline_opts=opts.SplitLineOpts(is_show=False), ), legend_opts=opts.LegendOpts(is_show=False), )) if len(extend_field) > 0: line = (Line().add_xaxis( xaxis_data=datetime_array).set_global_opts( xaxis_opts=opts.AxisOpts(type_="category"), legend_opts=opts.LegendOpts(is_show=True), )) for field in extend_field: field_value_array = df[field].tolist() line.add_yaxis( series_name=field, y_axis=field_value_array, is_smooth=is_smooth, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=2, opacity=0.8), label_opts=opts.LabelOpts(is_show=False), is_connect_nones=is_connect_nones, ) # Kline And Line kline = kline.overlap(line) # Grid Overlap + Bar grid_chart = Grid(init_opts=opts.InitOpts( width="100%", height="760px", animation_opts=opts.AnimationOpts(animation=False), )) grid_chart.add( kline, grid_opts=opts.GridOpts(pos_left="3.5%", pos_right="3.5%", height="60%"), ) grid_chart.add( bar, grid_opts=opts.GridOpts(pos_left="3.5%", pos_right="3.5%", pos_top="70%", height="16%"), ) grid_chart.render(os.path.join(save_path, "KLineChart.html"))
def line(delivery_dates, df): # line the vix FLINE_OPT = opts.LineStyleOpts(opacity=1, width=1.5) OLINE_OPT = opts.LineStyleOpts(opacity=0.9, width=1.2, type_='dashed') df['delivery'] = [10 + 5 * (idx in delivery_dates) for idx in df.index] warning_areas = get_warning_areas(df) # there is a bug in pyecharts, the colors are reversed # line.colors = ['crimson', 'gold', 'green', 'fuchsia', 'orchid', 'plum'] line = ( Line().add_xaxis(xaxis_data=df.index).add_yaxis( "vix", df[0], is_symbol_show=False, areastyle_opts=opts.AreaStyleOpts(opacity=0.2), linestyle_opts=FLINE_OPT, color='powderblue', markline_opts=opts.MarkLineOpts(data=[ opts.MarkLineItem(type_="min", name="ivl"), opts.MarkLineItem(type_="max", name="ivh"), ])).add_yaxis('gvz', df['gvz'], is_symbol_show=False, linestyle_opts=FLINE_OPT, color='olive', markline_opts=opts.MarkLineOpts(data=[ opts.MarkLineItem(type_="min", name="ivl"), opts.MarkLineItem(type_="max", name="ivh"), ])).add_yaxis( 'ovx', df['ovx'], is_symbol_show=False, linestyle_opts=FLINE_OPT, color='tan', # is_selected = False, markline_opts=opts.MarkLineOpts(data=[ opts.MarkLineItem(type_="min", name="ivl"), opts.MarkLineItem(type_="max", name="ivh"), ])).add_yaxis( "1", df[1], is_symbol_show=False, color='plum', linestyle_opts=OLINE_OPT).add_yaxis( "2", df[2], is_symbol_show=False, color='orchid', linestyle_opts=OLINE_OPT, is_selected=False).add_yaxis( "3", df[3], is_symbol_show=False, color='fuchsia', linestyle_opts=OLINE_OPT).add_yaxis( "4", df[4], is_symbol_show=False, color='green', linestyle_opts=OLINE_OPT, is_selected=False).add_yaxis( "5", df[5], is_symbol_show=False, color='gold', linestyle_opts=OLINE_OPT) # add delivery date mark, not a good idea, but worked. .add_yaxis("delivery", df['delivery'], is_symbol_show=False, color='crimson', is_step=True).set_series_opts( label_opts=opts.LabelOpts(is_show=False), markarea_opts=opts.MarkAreaOpts( is_silent=True, data=[ opts.MarkAreaItem(name="warn", x=(xs, xe)) for xs, xe in warning_areas ], itemstyle_opts=opts.ItemStyleOpts( color='#FFA54F10'))).set_global_opts( title_opts=opts.TitleOpts(title="vix", pos_left="0"), xaxis_opts=opts.AxisOpts( type_="category", is_scale=True, boundary_gap=False, axisline_opts=opts.AxisLineOpts( is_on_zero=False), splitline_opts=opts.SplitLineOpts( is_show=False), split_number=20, min_="dataMin", max_="dataMax", ), yaxis_opts=opts.AxisOpts( is_scale=True, splitline_opts=opts.SplitLineOpts( is_show=True)), tooltip_opts=opts.TooltipOpts( trigger="axis", axis_pointer_type="line"), datazoom_opts=opts.DataZoomOpts( type_="slider", range_start=50, range_end=100), )) return line
def grid_vertical(xaxis, taixin_yaxis, yali_yaxis, td_yaxis): max_taixin = max(taixin_yaxis) + 20 min_taixin = min(taixin_yaxis) - 60 if min_taixin <= 0: min_taixin = 0 line1 = (Line().add_xaxis(xaxis).add_yaxis( "胎心率", taixin_yaxis, label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False, markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_="average", name="胎心率平均值")]), markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_="max", name="胎心率最大值"), ]), ).add_yaxis("下限", [120, 120], markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_="average")])).add_yaxis( "上限", [160, 160], markline_opts=opts.MarkLineOpts( data=[opts.MarkLineItem(type_="average")])). add_yaxis( "胎动", td_yaxis, label_opts=opts.LabelOpts(is_show=False), markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_="None", name="胎动"), ]), ).set_global_opts( xaxis_opts=opts.AxisOpts( type_='value', interval=120, splitline_opts=opts.SplitLineOpts(is_show=True), axislabel_opts=opts.LabelOpts(formatter="{value}秒"), ), yaxis_opts=opts.AxisOpts( type_='value', interval=10, min_=min_taixin, max_=max_taixin, splitline_opts=opts.SplitLineOpts(is_show=True)), title_opts=opts.TitleOpts(title="eFM-60超声多普勒胎儿监护仪监测曲线图"), tooltip_opts=opts.TooltipOpts(trigger="axis"), toolbox_opts=opts.ToolboxOpts(is_show=True, ), ).set_series_opts( label_opts=opts.LabelOpts(is_show=False), markarea_opts=opts.MarkAreaOpts(data=[ opts.MarkAreaItem(name="合理区间", y=(120, 160), itemstyle_opts=opts.ItemStyleOpts( color="#A0D897", opacity=0.2)), ]))) line2 = ( Line().add_xaxis(xaxis).add_yaxis( "宫内压力", yali_yaxis, label_opts=opts.LabelOpts(is_show=False), is_symbol_show=False).set_global_opts( xaxis_opts=opts.AxisOpts( type_='value', interval=120, splitline_opts=opts.SplitLineOpts(is_show=True), axislabel_opts=opts.LabelOpts(formatter="{value}秒"), ), yaxis_opts=opts.AxisOpts( type_='value', interval=10, min_=0, max_=100, splitline_opts=opts.SplitLineOpts(is_show=True)), # title_opts=opts.TitleOpts(title="") tooltip_opts=opts.TooltipOpts(trigger="axis"), toolbox_opts=opts.ToolboxOpts(is_show=True), legend_opts=opts.LegendOpts(pos_top="50%"), ).set_series_opts(label_opts=opts.LabelOpts(is_show=False), )) # 把上面生成的两个图放进grid中并通过pos_top,pos_bottom, pos_left, pos_right设置其位置 grid = (Grid(init_opts=opts.InitOpts(width="3000px", height="600px")).add( line2, grid_opts=opts.GridOpts(pos_top='60%', pos_left='2%')).add( line1, grid_opts=opts.GridOpts(pos_bottom="60%", pos_left='2%'))) # 生成到本地网页形式打开,也可自己设置保存成png图片,因为网页的使用更方便,自己按情况使用 grid.render('1.html') # 输出保存为图片 make_snapshot(snapshot, grid.render(), "1.png") print(">>图表生成完毕!")
def signal_overview(price, trades=None, supplements=None, plot_options={}, f_name="1213.html"): figs_counts = len(supplements) legends_heights = (figs_counts * 5) left = 90 - legends_heights height = left / figs_counts sub_plots = [] fig_size = plot_options.setdefault("fig_size", ("1000px", "600px")) x_data = price.index.tolist() y_data = price.values.tolist() marks = supplements.get("marks") with_marks = True if marks is not None else False if with_marks: _ = pd.Series(index=price.index, data=np.arange(len(price))) marks_data = [ opts.MarkPointItem(coord=[(x_data[int(l)]), (y_data[int(l)])], itemstyle_opts=opts.ItemStyleOpts( color=plot_options.setdefault( v[0], colors[i]), opacity=0.6), symbol_size=20, symbol="pin") for i, v in enumerate(marks.items()) for l in _.reindex(v[1]).dropna().values.tolist() ] else: marks_data = [] with_trades = True if isinstance(trades, pd.Series) else False if with_trades: e_loc = [ price.index.get_loc(i) for i in trades.index.get_level_values(0).unique() ] ex_loc = [ price.index.get_loc(i) for i in trades.index.get_level_values(1).unique() ] pairs_loc = list(zip(e_loc, ex_loc)) (pairs_loc) _b = [{"gt": p[0], "lte": p[1], "color": "#CD6839"} for p in pairs_loc] _c = [{ "gt": pairs_loc[i][-1], "lte": p[0], "color": "#4A708B" } for i, p in enumerate(pairs_loc[1:])] _a = [{ "lte": pairs_loc[0][0], "color": "#4A708B" }, { "gt": pairs_loc[-1][-1], "color": colors[0] }] pieces = _a + _b + _c else: pieces = [] ds = np.unique(price.index.date) decor_ = price.groupby( price.index.date).apply(lambda x: [x.index[0], x.index[-1]]).loc[[ l[1] for l in list(filter(lambda x: x[0] % 2 == 0, enumerate(ds))) ]] data_zoom_axis = np.arange(figs_counts).astype(int).tolist() line = (Line( init_opts=opts.InitOpts(width=fig_size[0], height=fig_size[1]) ).add_xaxis(xaxis_data=x_data).add_yaxis( series_name="价格", y_axis=y_data, yaxis_index=0, is_smooth=True, is_symbol_show=False, is_hover_animation=False, linestyle_opts=opts.LineStyleOpts(width=2), markpoint_opts=opts.MarkPointOpts(data=marks_data, ), ).set_global_opts( title_opts=opts.TitleOpts(title="价格", pos_left='center', pos_top=str(figs_counts * 5) + "%"), toolbox_opts=opts.ToolboxOpts(is_show=True), tooltip_opts=opts.TooltipOpts( trigger="axis", axis_pointer_type="cross", border_width=1, ), legend_opts=opts.LegendOpts(pos_left="left"), axispointer_opts=opts.AxisPointerOpts(is_show=True, link=[{ "xAxisIndex": "all" }]), datazoom_opts=[ opts.DataZoomOpts(is_show=True, is_realtime=True, xaxis_index=data_zoom_axis, pos_top="5%", range_start=0, range_end=100, orient="horizontal", type_="inside"), opts.DataZoomOpts(type_="slider", xaxis_index=data_zoom_axis, pos_bottom="bottom"), ], yaxis_opts=opts.AxisOpts( is_scale=True, axistick_opts=opts.AxisTickOpts(is_inside=False), axispointer_opts=opts.AxisPointerOpts(is_show=True), axisline_opts=opts.AxisLineOpts(symbol='none'), splitline_opts=opts.SplitLineOpts(is_show=True)), xaxis_opts=opts.AxisOpts(is_show=False, ), visualmap_opts=opts.VisualMapOpts( is_show=False, is_piecewise=with_trades, dimension=0, pieces=pieces, ), ).set_series_opts(markarea_opts=opts.MarkAreaOpts(data=[ opts.MarkAreaItem( name="", x=(d[0], d[1]), itemstyle_opts=opts.ItemStyleOpts(color="#A1A9AF", opacity=0.2), ) for d in decor_ ]))) sub_plots.append(line) if with_marks: _ = supplements.pop("marks") if len(supplements) > 0: last_pic = list(supplements.keys())[-1] for i, s_1 in enumerate(supplements.items()): k, v = s_1[0], s_1[1] print(k) ls = Line( init_opts=opts.InitOpts(width=fig_size[0], height=fig_size[1])) ls = ls.add_xaxis(xaxis_data=price.index.tolist()) for j, s_2 in enumerate(v.items()): n, l = s_2[0], s_2[1] print(n) num = i * len(s_1) + j ls.add_yaxis( series_name=n, y_axis=l.tolist(), yaxis_index=len(sub_plots), linestyle_opts=opts.LineStyleOpts( width=2, color=plot_options.setdefault(n, colors[num])), label_opts=opts.LabelOpts(is_show=False), ) s = legends_heights + height * len(sub_plots) ls = ls.set_global_opts( title_opts=opts.TitleOpts(title=k, pos_left='center', pos_top=str(s) + "%"), legend_opts=opts.LegendOpts(pos_left="left", pos_top=str(len(sub_plots) * 5) + "%"), yaxis_opts=opts.AxisOpts( is_scale=True, axistick_opts=opts.AxisTickOpts(is_inside=False), axispointer_opts=opts.AxisPointerOpts(is_show=True), axisline_opts=opts.AxisLineOpts(symbol='none'), splitline_opts=opts.SplitLineOpts(is_show=True)), xaxis_opts=opts.AxisOpts(is_show=(k == last_pic), ), ).set_series_opts(markarea_opts=opts.MarkAreaOpts( data=[ opts.MarkAreaItem( name="", x=(d[0], d[1]), itemstyle_opts=opts.ItemStyleOpts(color="#A1A9AF", opacity=0.2), ) for d in decor_ ], is_silent=False, )) sub_plots.append(ls) pos = [ i + "%" for i in (height * np.arange(len(sub_plots)) + legends_heights + 4.3).astype(str) ] g = (Grid(init_opts=opts.InitOpts(width=fig_size[0], height=fig_size[1]))) for i, v in enumerate(sub_plots): g.add( chart=v, grid_opts=opts.GridOpts(pos_left=50, pos_right=50, pos_top=pos[i], height=str(height - 5) + "%"), ) g.render(f_name)
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()
axispointer_opts=opts.AxisPointerOpts(is_show=True) # 分隔线 splitline_opts=opts.SplitLineOpts(is_show=True), ) ) .set_series_opts( # 区域标记 markarea_opts=opts.MarkAreaOpts( is_silent=False, data=[ opts.MarkAreaItem( name='', x=(year-0.5,year+0.5), label_opts=opts.LabelOpts(is_show=False), itemstyle_opts=opts.ItemStyleOpts( color="#aaaaaa", opacity=0.1 ), ) ] ) ) ) #------------------------------------- 配件及其他常用格式详解 -------------------------------------# line=( Line( # 官方说明链接 下同 # 初始化 https://pyecharts.org/#/zh-cn/global_options?id=initopts%ef%bc%9a%e5%88%9d%e5%a7%8b%e5%8c%96%e9%85%8d%e7%bd%ae%e9%a1%b9 width = "900px", height = "500px", page_title = "Awesome-pyecharts",
), title_opts=opts.TitleOpts(title="各时段的订单数量与销售额"), tooltip_opts=opts.TooltipOpts(trigger="axis", axis_pointer_type="cross"), )) line = ( Line().add_xaxis(x_data).add_yaxis( "销售额", t3["analyze_t3.sales"].values.tolist(), yaxis_index=0, #color="#ff5798", #color="#BFEFFF", label_opts=opts.LabelOpts(is_show=False), ).set_series_opts(markarea_opts=opts.MarkAreaOpts(data=[ opts.MarkAreaItem(name="午高峰", x=("12", "15")), opts.MarkAreaItem(name="晚高峰", x=("17", "20")), ]))) # x_data = ["{}月".format(i) for i in range(1, 13)] # line = ( # Line() # .add_xaxis(x_data) # .add_yaxis( # "平均温度", # [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2], # # yaxis_index=2, # # color="#675bba", # # label_opts=opts.LabelOpts(is_show=False), # ) # )