def v_tradecost(self, start=None, end=yesterdayobj(), **vkwds): ''' visualization giving the average cost line together with netvalue line :param vkwds: keywords options for line.add() :returns: pyecharts.line ''' funddata = [] costdata = [] pprice = self.aim.price[self.aim.price['date'] <= end] if start is not None: pprice = pprice[pprice['date'] >= start] for _, row in pprice.iterrows(): date = row['date'] funddata.append([date, row['netvalue']]) if (date - self.cftable.iloc[0].date).days >= 0: cost = self.unitcost(date) costdata.append([date, cost]) line = Line() line.add('fundvalue', [1 for _ in range(len(funddata))], funddata, **vkwds) line.add('average_cost', [1 for _ in range(len(costdata))], costdata, is_datazoom_show=True, xaxis_type="time", **vkwds) return line
def print_results_echarts(df_hist_tmp, df_real_tmp, df_pred_tmp): print(df_pred_tmp) line = Line("Model results") line.add("Historic", df_hist_tmp.index.date, df_hist_tmp[target_col[0]].values, mark_point=["average"]) line.add("Prediction", df_pred_tmp.index.date, df_pred_tmp["prediction"], mark_line=["max", "average"]) # line.show_config() return line
def grid(self): line = Line('折线图', width=1200) attr = ['周一', '周二', '周三', '周四', '周五', '周六', '周日'] line.add('最高气温', attr, [11, 12, 14, 11, 12, 15, 16], mark_point=['max', 'min'], \ mark_line=['average']) line.add('最低气温', attr, [1, -1, 2, 5, 2, 3, 0], mark_point=['max', 'min'], \ mark_line=['average'], legend_pos='20%') attr = ['衬衫', '羊毛衫', '雪纺衫', '裤子', '高跟鞋', '袜子'] v1 = [11, 12, 14, 10, 11, 10] pie = Pie('饼图', title_pos='55%') pie.add('', attr, v1, radius=[45, 65], center=[65, 50], legend_pos='80%', \ legend_orient='vertical') grid = Grid() grid.add(line, grid_right='55%') grid.add(pie, grid_left='60%')
def v_netvalue(self, end=yesterdayobj(), benchmark=True, **vkwds): ''' visulaization on netvalue curve :param vkwds: parameters for the pyecharts options in line.add(), eg. yaxis_min=0.7 ''' a, b = self.comparison(end) xdata = [1 for _ in range(len(a))] ydata = [[row['date'], row['netvalue']] for _, row in a.iterrows()] ydata2 = [[row['date'], row['netvalue']] for _, row in b.iterrows()] line = Line() line.add('algorithm', xdata, ydata, is_datazoom_show=True, xaxis_type="time", **vkwds) if benchmark is True: line.add('benchmark', xdata, ydata2, is_datazoom_show=True, xaxis_type="time", **vkwds) return line
def DrawLine(city_names): line = Line('城市气温折线图') attrs1 = [] attrs2 = [] values1 = [] values2 = [] for cn in city_names: data = qr.get_data(cn) attrs1.append(cn) attrs2.append(cn) values1.append(data['Htemperature']) values2.append(data['Ltemperature']) line.add("最高气温", attrs1, values1, is_smooth=True, mark_point=["average"]) line.add("最低气温", attrs2, values2, is_smooth=True, mark_point=["average", "max"]) line.render('weatherLine.html')
def v_netvalue(self, end=yesterdayobj(), **vkwds): ''' 起点对齐归一的,各参考基金或指数的净值比较可视化 :param end: string or object of date, the end date of the line :param vkwds: pyechart line.add() options :returns: pyecharts.Line object ''' partprice = self.totprice[self.totprice['date'] <= end] xdata = [1 for _ in range(len(partprice))] ydatas = [] for fund in self.fundobjs: ydata = [[row['date'], row[fund.code]] for _, row in partprice.iterrows()] ydatas.append(ydata) line = Line() for i, fund in enumerate(self.fundobjs): line.add(fund.name, xdata, ydatas[i], is_datazoom_show=True, xaxis_type="time", **vkwds) return line
def v_techindex(self, end=yesterdayobj(), col=None, **vkwds): ''' visualization on netvalue curve and specified indicators :param end: date string or obj, the end date of the figure :param col: list, list of strings for price col name, eg.['MA5','BBI'] remember generate these indicators before the visualization :param vkwds: keywords option for pyecharts.Line().add(). eg, you may need is_symbol_show=False to hide the symbols on lines ''' partprice = self.price[self.price['date'] <= end] xdata = [1 for _ in range(len(partprice))] netvaldata = [[row['date'], row['netvalue']] for _, row in partprice.iterrows()] line = Line() line.add('netvalue', xdata, netvaldata, is_datazoom_show=True, xaxis_type="time", **vkwds) if col is not None: for ind in col: inddata = [[row['date'], row[ind]] for _, row in partprice.iterrows()] line.add(ind, xdata, inddata, is_datazoom_show=True, xaxis_type="time", **vkwds) return line
def v_totvalue(self, end=yesterdayobj(), **vkwds): ''' visualization on the total values daily change of the aim ''' valuedata = [] partp = self.aim.price[ self.aim.price['date'] >= self.cftable.iloc[0].date] partp = partp[partp['date'] <= end] for i, row in partp.iterrows(): date = row['date'] valuedata.append( [date, self.briefdailyreport(date).get('currentvalue', 0)]) line = Line() line.add('totvalue', [1 for _ in range(len(valuedata))], valuedata, is_datazoom_show=True, xaxis_type="time", **vkwds) return line
def kline_plot(self, ktype=0): df = self.cal_hadata() #画K线图数据 date = df.index.strftime('%Y%m%d').tolist() if ktype == 0: k_value = df[['adjopen', 'adjclose', 'adjlow', 'adjhigh']].values else: k_value = df[['ha_open', 'ha_close', 'ha_low', 'ha_high']].values #引入pyecharts画图使用的是0.5.11版本,新版命令需要重写 kline = Kline(self.name + '行情走势') kline.add('日K线图', date, k_value, is_datazoom_show=True, is_splitline_show=False) #加入5、20日均线 df['ma20'] = df.adjclose.rolling(20).mean() df['ma5'] = df.adjclose.rolling(5).mean() line = Line() v0 = df['ma5'].round(2).tolist() v = df['ma20'].round(2).tolist() line.add('5日均线', date, v0, is_symbol_show=False, line_width=2) line.add('20日均线', date, v, is_symbol_show=False, line_width=2) #成交量 bar = Bar() bar.add('成交量', date, df['vol'], tooltip_tragger='axis', is_legend_show=False, is_yaxis_show=False, yaxis_max=5 * max(df['vol'])) overlap = Overlap() overlap.add(kline) overlap.add(line, ) overlap.add(bar, yaxis_index=1, is_add_yaxis=True) return overlap
def generate_chart(self): if os.path.exists(self.outputDir+"chart/"): pass else: os.mkdir(self.outputDir+"chart/") line=Line("检测目标分析图") t1=['time','car','person','moto'] if os.path.exists(self.outputDir+"csv/count.csv"): with open(self.outputDir+"csv/count.csv",'r') as f: reader=csv.reader(f) result=np.array(list(reader)) for i in range(len(result[0])): if i==0: continue line.add(t1[i],result[0:,0],result[0:,i]) line.render(self.outputDir+'chart/count.html') t2=['time','CarIn','CarOut'] line2=Line("流量分析图") if os.path.exists(self.outputDir+"csv/flow.csv"): with open(self.outputDir+"csv/flow.csv",'r') as f: reader=csv.reader(f) result=np.array(list(reader)) for i in range(len(result[0])): if i==0: continue line2.add(t2[i],result[0:,0],result[0:,i]) line2.render(self.outputDir+"chart/flow.html") pie=Pie("速度区间分析图") if os.path.exists(self.outputDir+"csv/speed.csv"): with open(self.outputDir+"csv/speed.csv",'r') as f: reader=csv.reader(f) result=np.array(list(reader)) pie.add("速度区间",["[5km/h,10km/h)","[10km/h,15km/h)","[15km/h,20km/h)","[20km/h,25km/h)","[25km/h,30km/h)","[30km/h,40 km/h)","[40km/h,50 km/h)","[50km/h,+infinity)"],result[-1]) pie.render(self.outputDir+"chart/speed.html") self.saveIllegal()
def line(): attr = [ '教师', '教授', '副教授', '博导', '硕导', '国家级奖项', '省部级奖项', '院士', '荣誉学者', '专利' ] v1 = [100, 20, 15, 50, 40, 200, 200, 4, 5, 100] v2 = [150, 30, 40, 50, 30, 250, 200, 1, 2, 110] line = Line(width=1834, height=400) line.add( '北京大学', attr, v1, mark_point=['average', 'max', 'min'], # 标注点:平均值,最大值,最小值 mark_point_symbol='diamond', # 标注点:钻石形状 mark_point_textcolor='#40ff27') # 标注点:标注文本颜色 line.add( '清华大学', attr, v2, mark_point=['average', 'max', 'min'], mark_point_symbol='arrow', xaxis_name_size=20, yaxis_name_size=20, ) return line
# is_label_show=True, ) pie1.render('评分.html') #%% datas['dates'] = datas.date.apply(lambda x:pd.Timestamp(x).date()) datas['time'] = datas.date.apply(lambda x:pd.Timestamp(x).time().hour) num_date = datas.author.groupby(datas['dates']).count() # 评论数时间分布 chart = Line("评论数时间分布") chart.use_theme('dark') chart.add( '评论数时间分布',num_date.index, num_date.values, is_fill=True, line_opacity=0.2, area_opacity=0.4, symbol=None) chart.render('评论时间分布.html') # 好评字数分布 datalikes = datas.loc[datas.likes>5] datalikes['num'] = datalikes.content.apply(lambda x:len(x)) chart = Scatter("likes") chart.use_theme('dark') chart.add('likes', np.log(datalikes.likes), datalikes.num, is_visualmap=True, xaxis_name = 'log(评论字数)', ) chart.render('好评字数分布.html')
from pyecharts.charts import Line fruits = ['0-20', '20-50', '50-100', '100-200', '200以上'] #实例数目--一共 shop1_sales = [607, 711, 1038, 3451, 3876, 15409] shop2_sales = [4888, 7023, 3989, 5873, 8876, 6409] line = Line('折线图') line.add('扩充前A', fruits, shop1_sales, mark_point=['max']) line.add('扩充后B', fruits, shop2_sales, mark_point=['min']) line.show_config() line.render('./折线图.html')
ascending=False).to_frame().reset_index(), data.groupby(['所在区'])['总价(万元)'].mean().round(0).to_frame().reset_index(), on=['所在区']) bar = Bar("北京各区二手房价格") bar.add( "单价(元/平米)", zone_price['所在区'], zone_price['单价(元/平米)'], is_label_show=True, label_pos='inside', label_text_color='#000', is_toolbox_show=False, ) line = Line() line.add( "总价(万元)", zone_price['所在区'], zone_price['总价(万元)'], is_label_show=True, is_toolbox_show=False, ) overlap = Overlap(height=400, width=900) overlap.add(bar) overlap.add( line, yaxis_index=1, is_add_yaxis=True, ) overlap
# encoding: utf-8 from opendatatools import aqi from pyecharts.charts import Line import pandas as pd if __name__ == '__main__': df_aqi = aqi.get_daily_aqi_onecity('北京市') df_aqi.set_index('date', inplace=True) df_aqi.sort_index(ascending=True, inplace=True) df_aqi = df_aqi[df_aqi.index >= "2018-01-01"] axis_x = df_aqi.index axis_y = df_aqi['aqi'] line = Line("北京AQI趋势图") line.add("aqi curve for beijing", axis_x, axis_y, mark_point=["average"]) line.render("aqi_bj_curve.html")
LOGGER = logging.getLogger(__name__) if __name__ == '__main__': df = pd.read_csv('C:/git/machine_learning/machine_learning/data/资料01_商铺数据(2)(9).csv') df1 = df[df['comment'].str.contains('条')] df1['comment'] = df1['comment'].str.split(' ').str[0] df1['comment'] = df1['comment'].astype('int') df1 = df[df['price'].str.contains('¥')] df1['price'] = df1['price'].str.split('¥').str[-1] df1['price'] = df1['price'].astype('float') df1 = df1[df1['price'] > 50] import tushare as ts df = ts.get_day_all() df = df.round(2) df2 = ts.get_hist_data('600848') x = df2.index.tolist()[:20] y = df2[['open', 'close', 'low', 'high']] y1 = df2['open'].iloc[:20] ma5 = df2['ma5'] ma10 = df2['ma10'] ma20 = df2['ma20'] line = Line("我的第一个图表", "这里是副标题", width="800px", height="400px") line.add('开盘价', x, y1) line.render('C:/git/machine_learning/machine_learning/data/1.html')
"Express", "Home", "Johnny Depp", "Lena Dunham", "Lewis Hamilton", "KXAN", "Mary Ellen Mark", "Farrah Abraham", "Rita Ora", "Serena Williams", "NCAA baseball tournament", "Point Break" ] value = [ 10000, 6181, 4386, 4055, 2467, 2244, 1898, 1484, 1112, 965, 847, 582, 555, 550, 462, 366, 360, 282, 273, 265 ] wordcloud = WordCloud(width=1300, height=620) wordcloud.add("", name, value, word_size_range=[20, 100]) wordcloud.render(r".\my_first_Ciyun.html") """组合图""" line = Line("折线图", width=1200) attr = ["周一", "周二", "周三", "周四", "周五", "周六", "周日"] line.add("最高气温", attr, [11, 11, 15, 13, 12, 13, 10], mark_point=["max", "min"], mark_line=["average"]) line.add("最低气温", attr, [1, -2, 2, 5, 3, 2, 0], mark_point=["max", "min"], mark_line=["average"], legend_pos="20%") attr = ["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"] v1 = [11, 12, 13, 10, 10, 10] pie = Pie("饼图", title_pos="55%") pie.add("", attr, v1, radius=[45, 65], center=[65, 50], legend_pos="80%",
print('钱塘新区二手房最高价格:%.2f元/平方米' % max_price) print("钱塘新区二手房最低价格:%.2f元/平方米" % min_price) print("钱塘新区二手房平均价格:%.2f元/平方米" % mid_price) houselist.append('%.3f' % mid_price) print(houselist) house = [float(i) for i in houselist] print(house) house1 = Sort("地铁") house2 = Sort("大学") house3 = Sort("车") time = get_date_list("2020-02-14", "2020-03-18") a = Line("钱江新区房价变化图") a.add("平均价格", time, house, mark_line=["average"], mark_point=["max", "min"], xaxis_name="日期", yaxis_name="价格", yaxis_name_gap=60) a.add("地铁房", time, house1, mark_point=["max", "min"], xaxis_name="日期", yaxis_name="价格", yaxis_name_gap=60) a.add("学区房", time, house2, mark_point=["max", "min"], xaxis_name="日期",
def create_line(self, v): line = Line(TITLE_TEXT, TITLE_SUBTEXT) line.add("商家", ATTR, v, is_smooth=True, mark_line=["max", "average"]) snippet = TRANSLATOR.translate(line.options) options = snippet.as_snippet() return options