def chart_by_one_ver(by_type, pro_id, item, title, L=None): """ 生成项目特定版本下的不同分类的bug分布图表 :param by_type: 分类 :param pro_id: 项目标识 :param L: 资源类别名称、资源bug数量组成的列表 :param item: 图表图示 :param title: 图表title :return: html格式的图表 """ if L is None: L = [] result = getdata.get_issue_by_one_ver(by_type, pro_id) for v in result: L.append(v) xaxis_data = [] yaxis_data = [] else: print('L的类型必须为None,请检查') if len(L) != 0: xaxis_data = [x[0] for x in L] yaxis_data = [x[1] for x in L] v_name = [x[2] for x in L][0] title = ''.join([title, v_name, '版本']) bar = Bar() bar.add_xaxis(xaxis_data) bar.add_yaxis(item, yaxis_data) bar.set_global_opts(title_opts=opts.TitleOpts(title=title)) if os.path.exists(os.path.join(chart_path, '{}.html'.format(title))): os.remove(os.path.join(chart_path, '{}.html'.format(title))) bar.render(os.path.join(chart_path, '{}.html'.format(title))) else: print('没有数据可展示')
def main(): regions = ['hb', 'db', 'hd', 'hz', 'hn', 'xb', 'xn', 'gat'] # gat 的源码不规范 for index, region in enumerate(regions): # 获取url url = URL.format(region) html = get_url(url) # 规则网页 parse_html(html) # 数据可视化(数据分析) # 根据最低气温排序 ALL_DATA.sort(key=lambda data: data['min_temp']) data = ALL_DATA[:10] # 取前十个 # 从列表元素(字典),获取值。 # 方法1、遍历列表,获取列表的字典的值,再把这些值放入新列表;方法2、map # 全部城市 citys = list(map(lambda x: x['city'], data)) # 全部天气 min_temps = list(map(lambda x: x['min_temp'], data)) # pyechars bar = Bar() # 初始化 bar.add_xaxis(citys) bar.add_yaxis("城市", min_temps) # render 会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件 # 也可以传入路径参数,如 bar.render("mycharts.html") bar.render("mycharts.html")
def analyze_special_friends(): # 星标好友(很重要的人), 不让他看我的朋友圈的好友, 不看他朋友圈的好友, 消息置顶好友, 陌生人 star_friends, hide_my_post_friends, hide_his_post_friends, sticky_on_top_friends, stranger_friends = 0, 0, 0, 0, 0 for user in friends: # 星标好友为1,为0表示非星标,不存在星标选项的为陌生人 if ('StarFriend' in (user.raw).keys()): if ((user.raw)['StarFriend'] == 1): star_friends += 1 else: stranger_friends += 1 # 好友类型及权限:1和3好友,259和33027不让他看我的朋友圈,65539和65537和66051不看他的朋友圈,65795两项设置全禁止, 73731陌生人 if ((user.raw)['ContactFlag'] in [259, 33027, 65795]): hide_my_post_friends += 1 if ((user.raw)['ContactFlag'] in [66051, 65537, 65539, 65795]): hide_his_post_friends += 1 # 消息置顶好友为2051 2115 并不准确 if ((user.raw)['ContactFlag'] in [2051]): sticky_on_top_friends += 1 # 陌生人 仍然是不准确的 if ((user.raw)['ContactFlag'] in [73731]): stranger_friends += 1 bar = Bar() bar.add_xaxis(['星标', '不让他看我朋友圈', '不看他朋友圈', '消息置顶', '陌生人']) bar.add_yaxis('特殊好友分析', [ star_friends, hide_my_post_friends, hide_his_post_friends, sticky_on_top_friends, stranger_friends ]) bar.render('data/特殊好友分析.html')
def main(): urls=[ 'http://www.weather.com.cn/textFC/hb.shtml', 'http://www.weather.com.cn/textFC/db.shtml', 'http://www.weather.com.cn/textFC/hd.shtml', 'http://www.weather.com.cn/textFC/hz.shtml', 'http://www.weather.com.cn/textFC/hn.shtml', 'http://www.weather.com.cn/textFC/xb.shtml', 'http://www.weather.com.cn/textFC/xn.shtml', 'http://www.weather.com.cn/textFC/gat.shtml' ] for url in urls: parse_page(url) # 分析数据 # 根据最低气温排序 ALL_DATA.sort(key=lambda data:data['min_temp']) print(ALL_DATA) data = ALL_DATA[0:10] # 取名字 cities = list(map(lambda x:x['city'],data)) # 取气温 temps = list(map(lambda x:x['min_temp'],data)) print(cities,temps) chart = Bar() chart.add_xaxis(cities) chart.add_yaxis('',temps) chart.render('./temperature.html')
def draw_bar(sum_sheet): prov = sum_sheet[0].col_values(0, start_rowx=1, end_rowx=31) line = Bar() x1 = [] y1 = [] y2 = [] for i in range(19): x1.append(1997 + i) y1.append(sum_sheet[i].cell_value(1, 1)) y2.append(sum_sheet[i].cell_value(9, 1)) line.add_xaxis(x1) line.set_global_opts(xaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(font_size=10, interval=0, rotate=45))) line.add_yaxis("Beijing", y1) line.add_yaxis("Shanghai", y2) line.render("北京上海年CO2排放量变化图.html") bar = Bar() x2 = [] for i in range(30): x2.append(prov[i]) y3 = sum_sheet[0].col_values(1, start_rowx=1, end_rowx=31) y4 = sum_sheet[-1].col_values(1, start_rowx=1, end_rowx=31) bar.add_xaxis(x2) bar.set_global_opts(xaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(font_size=10, interval=0, rotate=45))) bar.add_yaxis("1997", y3) bar.add_yaxis("2015", y4) bar.render("1997与2015 各省CO2年排放量对比.html")
def do_charts(): nvshen = pd.read_csv('nvshen.csv') nvshen.sort_values('weight_score', ascending=False, inplace=True) bar = Bar() count_top = nvshen['count'][0:10].values.tolist() count_bottom = nvshen['count'][-10:-1].values.tolist() count = [''.join(list(filter(str.isdigit, i))) for i in count_top] + \ [''.join(list(filter(str.isdigit, i))) for i in count_bottom] name_top = nvshen['name'][0:10] name_bottom = nvshen['name'][-10:-1] name = name_top.values.tolist() + name_bottom.values.tolist() score_top = nvshen["weight_score"][0:10] score_bottom = nvshen["weight_score"][-10:-1] score = score_top.values.tolist() + score_bottom.values.tolist() bar.add_xaxis(name) bar.add_yaxis("女神得分/百分制", score, gap="0%") bar.add_yaxis("打分人数/万", count, gap="0%") bar.set_global_opts( title_opts=opts.TitleOpts(title="女神大会", subtitle="女神大排名-top10"), datazoom_opts=opts.DataZoomOpts(is_show=True, orient="vertical"), xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=-45)), toolbox_opts=opts.ToolboxOpts()) bar.render('女神大排名-top10.html') word_name = nvshen['name'].values.tolist() word_value = nvshen["weight_score"].values.tolist() words = [i for i in zip(word_name, word_value)] wordcloud = WordCloud() wordcloud.add("", words, word_size_range=[10, 40], shape='circle') wordcloud.render("女神词云.html")
def main(): urls = [ 'http://www.weather.com.cn/textFC/hb.shtml', 'http://www.weather.com.cn/textFC/db.shtml', 'http://www.weather.com.cn/textFC/hd.shtml', 'http://www.weather.com.cn/textFC/hz.shtml', 'http://www.weather.com.cn/textFC/hn.shtml', 'http://www.weather.com.cn/textFC/xb.shtml', 'http://www.weather.com.cn/textFC/xn.shtml', 'http://www.weather.com.cn/textFC/gat.shtml' ] for url in urls: parse_page(url) # 分析数据 # 根据最低气温进行排序 ALL_DATA.sort(key=lambda data: data['min_temp']) # print(ALL_DATA) data = ALL_DATA[0:10] cities = map(lambda x: x['city'], data) min_temp = map(lambda x: x['min_temp'], data) bar = Bar() bar.add_xaxis(list(cities)) bar.add_yaxis("今日中国最低温度", list(min_temp)) bar.render("mycharts.html")
def plot_data(condition,title): #distinct删除重复值 table_names = pd.read_sql( "select name from sqlite_master where type='table' order by name",engine).values if 'sqlite_sequence' in table_names: table_names = table_names[:-1] all_tables = table_names temp = None n = 1 for table in all_tables[:100]: sql=f"select distinct * from '{table[0]}' where trade_date>'20190101' and "+ condition data=pd.read_sql(sql,engine) print(f"第{n}/{len(all_tables[:100])}:{table[0]}已筛选!") if temp is None: temp = data else: temp = pd.concat([data, temp], axis=0) n += 1 count_=temp.groupby('trade_date')['ts_code'].count() # print(count_) attr=count_.index.values.tolist() v1=count_.values.tolist() bar=Bar() # # bar= BAR(title) bar.add_xaxis(attr) bar.add_yaxis('',v1) # # bar.add('',attr,v1,is_splitline_show=False,is_datazoom_show=True,linewidth=2) # bar.render() bar.render(title+'.html')
def create_cut_likes(df): # 将数据分段 Bins = [ 0, 1000000, 5000000, 10000000, 25000000, 50000000, 100000000, 5000000000 ] Labels = [ '0-100', '100-500', '500-1000', '1000-2500', '2500-5000', '5000-10000', '10000以上' ] len_stage = pd.cut(df['likes'], bins=Bins, labels=Labels).value_counts().sort_index() # 获取数据 attr = len_stage.index.tolist() v1 = len_stage.values.tolist() # 生成柱状图 bar = Bar(init_opts=opts.InitOpts(width="800px", height="400px")) bar.add_xaxis(attr) bar.add_yaxis("", v1) bar.set_global_opts( title_opts=opts.TitleOpts(title="抖音大V点赞数分布情况(万)", pos_left="center", pos_top="18"), toolbox_opts=opts.ToolboxOpts(is_show=True, feature={"saveAsImage": {}}), yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts( is_show=True))) bar.set_series_opts( label_opts=opts.LabelOpts(is_show=True, position="top", color="black")) bar.render("抖音大V点赞数分布情况(万).html")
def draw_amount_bar(self): """ 画出股票的成交量和 需要传入的数据是股票的["amount" :return: """ # SC = "000021.SZ" Df_s1 = Read_One_Stock(self.SC).select_col("vol", "amount") length = Df_s1.shape[0] Df_s1.sort_values("trade_date", inplace=True) Df_s1.index = list(range(length)) amount = np.array(Df_s1["amount"]).tolist() date = np.array(Df_s1["trade_date"], dtype=np.string_).tolist() bar = Bar() bar.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()], title_opts=opts.TitleOpts(title="K-Line of {}".format(self.SC))) bar.add_xaxis(date) bar.add_yaxis("Amounts", amount, label_opts=opts.LabelOpts(is_show=False)) bar.render("./Plots/{} Amount Bar Plot.html".format(self.SC))
def create_likes(df): # 排序,降序 df = df.sort_values('likes', ascending=False) # 获取TOP10的数据 attr = df['name'][0:10] v1 = [float('%.1f' % (float(i) / 100000000)) for i in df['likes'][0:10]] # 初始化配置 bar = Bar(init_opts=opts.InitOpts(width="800px", height="400px")) # x轴数据 bar.add_xaxis(list(reversed(attr.tolist()))) # y轴数据 bar.add_yaxis("", list(reversed(v1))) # 设置全局配置项,标题、工具箱(下载图片)、y轴分割线 bar.set_global_opts( title_opts=opts.TitleOpts(title="抖音大V点赞数TOP10(亿)", pos_left="center", pos_top="18"), toolbox_opts=opts.ToolboxOpts(is_show=True, feature={"saveAsImage": {}}), xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts( is_show=True))) # 设置系列配置项,标签样式 bar.set_series_opts(label_opts=opts.LabelOpts( is_show=True, position="right", color="black")) bar.reversal_axis() bar.render("抖音大V点赞数TOP10(亿).html")
def create_abroad(df): # 筛选数据 df = df[(df["country"] != "中国") & (df["country"] != "") & (df["country"] != "暂不设置") & (df["country"] != "China")] df1 = df.copy() # 数据替换 df1["country"] = df1["country"].str.replace("United States", "美国").replace("大韩民国", "韩国") # 分组计数 df_num = df1.groupby("country")["country"].agg( count="count").reset_index().sort_values(by="count", ascending=False) df_country = df_num[:8]["country"].values.tolist() df_count = df_num[:8]["count"].values.tolist() # 初始化配置 bar = Bar(init_opts=opts.InitOpts(width="800px", height="400px")) bar.add_xaxis(df_country) bar.add_yaxis("", df_count) bar.set_global_opts( title_opts=opts.TitleOpts(title="抖音大V国外分布TOP10", pos_left="center", pos_top="18"), toolbox_opts=opts.ToolboxOpts(is_show=True, feature={"saveAsImage": {}}), yaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts( is_show=True))) bar.set_series_opts( label_opts=opts.LabelOpts(is_show=True, position="top", color="black")) bar.render("抖音大V国外分布TOP10.html")
def create_avg_likes(df): # 筛选 df = df[df['videos'] > 0] # 计算单个视频平均点赞数 df.eval('result = likes/(videos*10000)', inplace=True) df['result'] = df['result'].round(decimals=1) df = df.sort_values('result', ascending=False) # 取TOP10 attr = df['name'][0:10] v1 = ['%.1f' % (float(i)) for i in df['result'][0:10]] # 初始化配置 bar = Bar(init_opts=opts.InitOpts(width="800px", height="400px")) # 添加数据 bar.add_xaxis(list(reversed(attr.tolist()))) bar.add_yaxis("", list(reversed(v1))) # 设置全局配置项,标题、工具箱(下载图片)、y轴分割线 bar.set_global_opts( title_opts=opts.TitleOpts(title="抖音大V平均视频点赞数TOP10(万)", pos_left="center", pos_top="18"), toolbox_opts=opts.ToolboxOpts(is_show=True, feature={"saveAsImage": {}}), xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts( is_show=True))) # 设置系列配置项 bar.set_series_opts(label_opts=opts.LabelOpts( is_show=True, position="right", color="black")) # 翻转xy轴 bar.reversal_axis() bar.render("抖音大V平均视频点赞数TOP10(万).html")
def city_company_scale_chart(self): """前10城市的企业阶段""" city_company_scale = pd.crosstab(self.frame.city, self.frame.company_scale, margins=True).sort_values( by='All', ascending=False)[:10] city_company_scale = city_company_scale.drop('All', axis=0).drop('All', axis=1) html_path = os.path.join( create_or_get_directory(os.path.join('report', 'single')), 'city_company_scale_chart.html') bar = Bar(init_opts=opts.InitOpts(width="60%")) bar.add_xaxis(list(city_company_scale.index)) for i in range(len(list(city_company_scale.T.index))): bar.add_yaxis(city_company_scale.T.index[i], [str(v) for v in city_company_scale.T.values[i]]) bar.set_global_opts( legend_opts=opts.LegendOpts(is_show=False), xaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(rotate=-20, color='red')), yaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts( color='red')), ) bar.render(html_path) script_string = self.get_javascript_string(html_path) self.set_report_javascript(script_string, 'city_company_scale_chart') self.right_charts.append({ 'title': '前10城市的企业阶段', 'name': 'city_company_scale_chart' })
def main(): urls = [ 'http://www.weather.com.cn/textFC/hb.shtml', 'http://www.weather.com.cn/textFC/db.shtml', 'http://www.weather.com.cn/textFC/hd.shtml', 'http://www.weather.com.cn/textFC/hz.shtml', 'http://www.weather.com.cn/textFC/hn.shtml', 'http://www.weather.com.cn/textFC/xb.shtml', 'http://www.weather.com.cn/textFC/xn.shtml', 'http://www.weather.com.cn/textFC/gat.shtml' ] for url in urls: parse_page(url) # 数据分析 根据最低气温排序 ALL_DATA.sort(key=lambda data: data["min_temp"]) # 通过key指定根据什么排序 # data 是ALL_DATA列表中每一行的字典数据, 根据data["min_temp"]返回值排序 data = ALL_DATA[0:10] # 最低气温排前十的城市/区 cities = list(map(lambda x: x['city'], data)) temps = list(map(lambda x: x['min_temp'], data)) chart = Bar() # 给这个图取名 #chart.add(cities,temps,is_more_utils=True) chart.add_xaxis(cities) chart.add_yaxis("最低气温表", temps) chart.render('temperature.html')
def main(): urls = [ "http://www.weather.com.cn/textFC/hz.shtml", "http://www.weather.com.cn/textFC/hb.shtml", "http://www.weather.com.cn/textFC/hn.shtml", "http://www.weather.com.cn/textFC/hd.shtml", "http://www.weather.com.cn/textFC/db.shtml", "http://www.weather.com.cn/textFC/xb.shtml", "http://www.weather.com.cn/textFC/xn.shtml", "http://www.weather.com.cn/textFC/gat.shtml", ] for url in urls: parse_page(url) ALL_DATA.sort(key=lambda data: data['max_temp'], reverse=True) data = ALL_DATA[0:10] print(data) cities = list(map(lambda x: x['city'], data)) temp_max = list(map(lambda x: x['max_temp'], data)) chart = Bar() chart.add_xaxis(cities) chart.add_yaxis('气温', temp_max) chart.render('temperature.html')
def bar(x, y): bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.MACARONS)) bar.add_xaxis(x) bar.add_yaxis("盈利", y) bar.set_global_opts(title_opts=opts.TitleOpts(title="380平台月盈利")) bar.set_series_opts(label_opts=opts.LabelOpts(is_show=False)) bar.render('../graph/4.1平台月盈利.html')
def relation_count(): """ 统计每种关系的次数 数据来源ref:https://github.com/DesertsX/gulius-projects/blob/master/3_InteractiveGraph_HongLouMeng/InteractiveGraph_HongLouMeng.json :return: """ with codecs.open('relative.json', 'r', encoding='utf-8') as json_str: json_dict = json.load(json_str) edges = json_dict['data']['edges'] edges_df = pd.DataFrame(edges) edges_rela = edges_df.label.value_counts() # 所有关系 relations = edges_df.label relations = relations.tolist() relations = list(set(relations)) # 每种关系对应的频数 rela_counts = [] for each in relations: rela_counts.append(int(edges_rela[each])) # 柱状图 bar = Bar() bar.add_xaxis(relations) bar.add_yaxis('频次', rela_counts) bar.set_global_opts(title_opts=opts.TitleOpts(title="红楼梦关系频次表")) bar.render('relation_count.html')
def testBar(self): bar = Bar() bar.add_xaxis(["衬衫", "毛衣", "领带", "裤子", "风衣", "高跟鞋", "袜子"]) bar.add_yaxis("商家A", [114, 55, 27, 101, 125, 27, 105]) bar.add_yaxis("商家B", [57, 134, 137, 129, 145, 60, 49]) bar.set_global_opts(title_opts=opts.TitleOpts(title="某商场销售情况")) bar.render()
def make_bar_rating(filename): # 定义各个文件名 # title = filename.split('/')[-1].split('.')[0] title = os.path.basename(filename).split('.')[0] target_dir = os.path.join( os.path.abspath(os.path.dirname(os.path.dirname(__file__))), "analyse_data", "bar_echarts_pic") if not os.path.exists(target_dir): os.mkdir(target_dir) print("分析结果保存在 ", target_dir, " 文件夹下...") htmlName = title + '.html' pngName = title + '.png' htmlPath = os.path.join(target_dir, htmlName) pngPath = os.path.join(target_dir, pngName) # 导入数据,并删除无关列 rows = pd.read_csv(filename, encoding='utf-8', dtype=str) to_drop = ['用户', '是否看过', '评论时间', '有用数', '评论'] rows.drop(to_drop, axis=1, inplace=True) # 数据清洗 rows = rows[rows['评分'].isin(['力荐', '推荐', '还行', '较差', '很差'])] # 数据统计 result_rating = rows.groupby('评分')['评分'].count() # 转换类型 pd.Series -> py.dict values = {i: v for i, v in result_rating.items()} # pyecharts 生成柱状图 bar = Bar() bar.add_xaxis(['力荐', '推荐', '还行', '较差', '很差']) bar.add_yaxis( title, [values['力荐'], values['推荐'], values['还行'], values['较差'], values['很差']]) bar.render(htmlPath)
def main(): urls = [ '华北地区天气预报.html', '东北地区天气预报.html', '华东地区天气预报.html', '华中地区天气预报.html', '华南地区天气预报.html', '西北地区天气预报.html', '西南地区天气预报.html', '港澳台地区天气预报.html', ] for url in urls: parse_page(url) # 分析数据 # 根据最低气温进行排序 ALL_DATA.sort(key=lambda data: data['min_temp']) # print(ALL_DATA) data = ALL_DATA[0:10] cities = map(lambda x: x['city'], data) min_temp = map(lambda x: x['min_temp'], data) bar = Bar() bar.add_xaxis(list(cities)) bar.add_yaxis("今日中国最低温度", list(min_temp)) bar.render("mycharts_local.html")
def test(): bar = Bar() bar.add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"]) bar.add_yaxis("商家A", [5, 20, 36, 10, 75, 90]) # render 会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件 # 也可以传入路径参数,如 bar.render("mycharts.html") bar.render('charts/mycharts.html')
def main(): urls = [ "http://www.weather.com.cn/textFC/hb.shtml", "http://www.weather.com.cn/textFC/db.shtml", "http://www.weather.com.cn/textFC/hd.shtml", "http://www.weather.com.cn/textFC/hz.shtml", "http://www.weather.com.cn/textFC/hn.shtml", "http://www.weather.com.cn/textFC/xb.shtml", "http://www.weather.com.cn/textFC/xn.shtml", "http://www.weather.com.cn/textFC/gat.shtml" ] for url in urls: parse_page(url) # 数据分析 # 根据最低气温进行排序 # def sorr_key(data): # min_temp = data["min_temp"] # return min_temp ALL_DATA.sort(key=lambda data:data["min_temp"]) data = ALL_DATA[0:10] cities = list(map(lambda x:x['city'],data)) temps = list(map(lambda x:x['min_temp'],data)) chart = Bar("中国天气最低温度排行榜") chart.add('',cities,temps) chart.render('temperature.html')
def coincedence(place) -> Bar: place = np.array(place) foo = place[:, 1].astype(np.float) order = np.argsort(foo) k = 0 place1 = np.copy(place) for i in order: place1[k] = place[i, :] k = k + 1 place = place1 bar = Bar() bar.add_xaxis(list(place[:, 0])) bar.add_yaxis("热度", list(place[:, 1])) bar.set_global_opts(title_opts=opts.TitleOpts(title="外来旅游人口相关度")) bar.set_global_opts(xaxis_opts=opts.AxisOpts(boundary_gap=1, interval=0, axislabel_opts={"rotate": 45}), toolbox_opts=opts.ToolboxOpts(is_show=True), datazoom_opts=[ opts.DataZoomOpts(range_start=0, range_end=100, is_zoom_lock=False) ]) #bar.set_global_opts(xaxis_opts=opts.AxisTickOpts(is_align_with_label=0)) bar.set_series_opts(label_opts=opts.LabelOpts(font_size=9)) bar.width = 1200 bar.render(path="外来旅游人口相关度.html") return True
def bar(self,df,legend,title,path): ''' 柱状图 :param df: 要操作的数据 :param legend: 图例 :param title: 报表标题 :param path: 保存路径 :return: ''' tmp = df.value_counts() x = list(tmp.index) y = list(tmp) bar = Bar() bar.add_xaxis(x) bar.add_yaxis(legend, y, category_gap="60%") bar.set_series_opts(itemstyle_opts={ "normal": { "color": utils.JsCode("""new echarts.graphic.LinearGradient(0, 0, 0, 1, [{ offset: 0, color: 'rgba(0, 244, 255, 1)' }, { offset: 1, color: 'rgba(0, 77, 167, 1)' }], false)"""), "barBorderRadius": [30, 30, 30, 30], "shadowColor": 'rgb(0, 160, 221)', }}) bar.set_global_opts(title_opts=opts.TitleOpts(title=title)) bar.render(path + '/' + title + '.html')
def generate_bar(self, x_axis, y_axis): bar = Bar(init_opts=opts.InitOpts(width="1280px", height="720px")) bar.add_xaxis(x_axis) bar.add_yaxis("", y_axis) bar.set_global_opts(xaxis_opts=opts.AxisOpts( axislabel_opts=opts.LabelOpts(rotate=10))) bar.render('bar.html')
def analysis_score(self): evaluate = {} with open(self.score_file, 'r', encoding='utf-8') as f: for i in f.readlines(): i = re.sub(r"[A-Za-z0-9\-\:]", "", i) i = i.strip() # 去掉每行的换行符 # 如果这个没出现过,就初始化为1 if i not in evaluate: evaluate[i] = 1 logger.logger.debug(evaluate) else: # 如果已经出现过了,就在自加1 evaluate[i] += 1 logger.logger.debug(evaluate) logger.logger.info(evaluate) bar = Bar() eva = [] count = [] for k, v in evaluate.items(): if k != '': eva.append(k) count.append(v) bar.add_xaxis(eva) # 柱状图x轴 logger.logger.info('xaxis'+str(eva)) bar.add_yaxis("评价", count) # 柱状图y轴 logger.logger.info('yaxis'+str(count)) bar.set_global_opts(title_opts=opts.TitleOpts(title="隐秘的角落 豆瓣评分")) # 生成可视化图表 bar.render(self.path+"\\score.html")
def pye_bar(x_data, y_data, ylabel): bar = Bar(init_opts=opts.InitOpts(theme=ThemeType.CHALK)) bar.add_xaxis(x_data) bar.add_yaxis(ylabel, y_data) # render 会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件 # 也可以传入路径参数,如 bar.render("mycharts.html") bar.render()
def drawbar(arrt, value, name): # 图表初始化配置 init_opts = opts.InitOpts(page_title=name, height="700px") bar = Bar(init_opts=init_opts) # 标题配置 title = opts.TitleOpts(title=name, pos_left='center') # 图例配置 legend_opts = opts.LegendOpts(pos_top="5%", pos_left="15%") # 工具箱配置 # feature = opts.ToolBoxFeatureOpts(save_as_image=True, restore=True, data_view=True, data_zoom=True) # 工具箱配置 toolbox_opts = opts.ToolboxOpts(pos_top="5%", pos_right="30%") bar.set_global_opts( title_opts=title, legend_opts=legend_opts, toolbox_opts=toolbox_opts, # 区域缩放配置项 datazoom_opts=opts.DataZoomOpts(), ) # add_yaxis bar.add_xaxis(arrt) # 渐变色 bar.add_yaxis( "", value, gap="0%", category_gap="30%", # 自定义颜色 itemstyle_opts=opts.ItemStyleOpts( color=JsCode("""new echarts.graphic.LinearGradient(0, 0, 1, 0, [{ offset: 0, color: 'rgb(39, 117, 182)' }, { offset: 0.5, color: 'rgb(147, 181,207)' }, { offset: 1, color: 'rgb(35, 118, 183)' }], false)""")), ) bar.set_series_opts( label_opts=opts.LabelOpts(is_show=False), markline_opts=opts.MarkLineOpts(data=[ opts.MarkLineItem(type_="min", name="最小值"), opts.MarkLineItem(type_="max", name="最大值"), opts.MarkLineItem(type_="average", name="平均值"), ]), markpoint_opts=opts.MarkPointOpts(data=[ opts.MarkPointItem(type_="max", name="最大值"), opts.MarkPointItem(type_="min", name="最小值"), opts.MarkPointItem(type_="average", name="平均值"), ]), ) bar.render('{0}.html'.format(name))
def test_bar_colors(fake_writer): c = Bar().add_xaxis(["A", "B", "C"]).add_yaxis("series0", [1, 2, 4]) c.set_colors(["#AABBCC", "#BBCCDD", "#CCDDEE"] + c.colors) c.render() _, content = fake_writer.call_args[0] assert_in("#AABBCC", content) assert_in("#BBCCDD", content) assert_in("#CCDDEE", content)