Beispiel #1
0
from pyecharts.charts import Line
import pyecharts.options as opts

line = Line()
datax = [str(x) for x in range(1995, 2010)]  # 横坐标必须是字符串
datay = [
    0.32, 0.32, 0.32, 0.32, 0.33, 0.33, 0.34, 0.37, 0.37, 0.37, 0.37, 0.39,
    0.41, 0.42, 0.44
]

line.add_xaxis(datax)
line.add_yaxis('Price', datay, is_step=True)

line.set_global_opts(title_opts=opts.TitleOpts(title='美国邮费阶梯图'),
                     yaxis_opts=opts.AxisOpts(min_=0.3, max_=0.45))

line.render('step.html')
Beispiel #2
0
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')
Beispiel #3
0
from pyecharts.charts import Line
from pyecharts import options

# 准备数据
cuntry = ['美国', '巴西', '印度', '俄罗斯']
data1 = [10000000, 600000, 5000000, 300000]

# 实例化图表对象

line = Line()

# 关联数据
line.add_xaxis(cuntry)
line.add_yaxis(series_name='感染人数', y_axis=data1, is_smooth=True)
# is_smooth=True曲线
# 配置
# 全局设置
line.set_global_opts(title_opts=options.TitleOpts(title='世界严重感染国家'),
                     toolbox_opts=options.ToolboxOpts())
# 系列设置
line.set_series_opts(markline_opts=options.MarkLineOpts(data=[
    options.MarkLineItem(name='平均值', type_='average'),
]))

line.render('templates/折线图.html')
Beispiel #4
0
# Confirmed_diagnosis_data=year_rate

# 2. 创建图表对象
line = Line()

# 3. 关联数据
line.add_xaxis(newdate)  # x轴

line.add_yaxis(
    "30MA",
    thirty,
    # 设置折线是否平滑
    is_smooth=False,
    is_hover_animation=True,
    is_symbol_show=False)
# 4. 设置
line.set_series_opts(markline_opts=options.MarkLineOpts(
    # 设置平均值的标记线
    data=[
        options.MarkPointItem(type_="min", name="最小值"),
        # 设置最大值的标记线
        options.MarkPointItem(type_="max", name="最大值")
    ]))
line.set_global_opts(
    xaxis_opts=options.AxisOpts(axislabel_opts=options.LabelOpts(rotate=-30)),
    yaxis_opts=options.AxisOpts(name='每日年化收益率'),
    title_opts=options.TitleOpts(title="每日年化收益率变化曲线", subtitle="副标题"))

# 5. 数据渲染
line.render("plot_changqi_zhexian.html")
def draw_line_picture(xaxis_data, data, to_file, unit, svg_name, stack,
                      y_name):
    """
    多条线,是否堆叠要确认下
    :param label_right:
    :param y_name: y轴名称
    :param stack: boolean, 是否要堆叠
    :param xaxis_data: x轴
    :param data: {series_name, data}
    :param svg_name: svg文件
    :param to_file: 结果文件
    :param unit: 横轴的数值的单位(加在每个横轴值后面,比如 月)
    :return:
    """
    xaxis_data = [str(i) + unit for i in xaxis_data]
    bar = Line(init_opts=opts.InitOpts(
        width="800px", height="600px", bg_color='white')).add_xaxis(
            xaxis_data=xaxis_data,
            # add_xaxis=opts.LabelOpts(formatter="{value}" + unit),
        )
    for series_name, y_axis in data.items():
        if stack:
            bar = bar.add_yaxis(
                series_name=series_name,
                is_smooth=True,
                symbol="circle",
                # symbol_size=8,
                stack='1',
                is_symbol_show=False,
                # color="#d14a61",
                y_axis=y_axis,
                yaxis_index=0,
                label_opts=opts.LabelOpts(is_show=False),
                # linestyle_opts=opts.LineStyleOpts(width=2),
                areastyle_opts=opts.AreaStyleOpts(opacity=1))
        else:
            bar = bar.add_yaxis(
                series_name=series_name,
                is_smooth=True,
                symbol="circle",
                symbol_size=8,
                is_symbol_show=True,
                # color="#d14a61",
                y_axis=y_axis,
                yaxis_index=0,
                label_opts=opts.LabelOpts(is_show=False),
                linestyle_opts=opts.LineStyleOpts(width=2),
            )
    bar = bar.set_global_opts(
        yaxis_opts=opts.AxisOpts(
            type_="value",
            name=y_name,
            name_textstyle_opts=opts.TextStyleOpts(font_size=25),
            # min_=0,
            # max_=250,
            position="left",
            offset=0,
            axisline_opts=opts.AxisLineOpts(
                linestyle_opts=opts.LineStyleOpts()),
            axislabel_opts=opts.LabelOpts(formatter="{value}", font_size=25),
        ),
        xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(
            formatter="{value}", font_size=25, interval=0), ),
        tooltip_opts=opts.TooltipOpts(trigger="axis",
                                      axis_pointer_type="cross"),
        toolbox_opts=opts.ToolboxOpts(feature=opts.ToolBoxFeatureOpts(
            data_zoom=opts.ToolBoxFeatureDataZoomOpts(is_show=False),
            # brush=opts.ToolBoxFeatureBrushOpts(is_show=False),
        )),
        legend_opts=opts.LegendOpts(
            pos_left="12%",
            pos_top="10%",
            orient="vertical",
            # backgroundColor='rgb(255, 255, 255)',
            item_width=40,
            item_height=20,
            textstyle_opts=opts.TextStyleOpts(font_size=25)),
    )
    make_snapshot(snapshot, bar.render(to_file), svg_name)  # 生成svg图片
Beispiel #6
0
def process_prepare_data(singer_id):
    # 找出歌手所有歌曲
    all_songs = db.scan(0, match="song:*", count=10000)
    target_songs = []
    total_score = 0
    emotion_list = []
    words_count = Counter()
    maker_count = Counter()
    for song in all_songs[1]:
        sid = db.hget(song, "singer_id")
        if sid.decode("utf-8") == str(singer_id):
            target_songs.append(song)

    # 取得所有歌曲并排序
    sorted_songs = [(song, int(db.hget(song, "comment_count").decode("utf-8")))
                    for song in target_songs]
    sorted_songs.sort(key=lambda x: x[1], reverse=True)
    # log("最热度的前20首歌曲为:{}".format(
    #     [db.hget(song[0], "name").decode("utf-8").replace("\n", "") for song in sorted_songs[:20]]))
    # log("最冷门的前20首歌曲为:{}".format(
    #     [db.hget(song[0], "name").decode("utf-8").replace("\n", "") for song in sorted_songs[-20:]]))

    for song in sorted_songs:
        # 歌词处理 song: (song_id, comment_count)
        text, maker_info = merge_lyric_text(song[0])
        # 歌词的情绪分析
        song_name = db.hget(song[0], "name").decode("utf-8")
        song_score = db.get(b'score:' + song[0])
        if song_score is None:
            song_score = process_emotion(text)
            db.set(b'score:' + song[0], song_score)
            log("歌曲 {} 未发现情绪分,已计算后存入Redis".format(song_name.replace("\n", "")))
        total_score += float(song_score)
        emotion_list.append((song_name, float(song_score)))
        # log("正在处理第{}首歌曲,{}的情绪分为{:.2f}".format(sorted_songs.index(song) + 1, song_name.replace("\n", ""),
        #                                       float(song_score)))

        for line in maker_info.split("\n"):
            if "作词" in line:
                line = SnowNLP(line).han
                if ":" in line:
                    maker_count[line.split(":")[1].strip()] += 1
                else:
                    maker_count[line.split(":")[1].strip()] += 1
        # 词频统计
        words_count.update(process_frequency(text))
        maker_analysis(maker_info)

    # ----图表部分----

    # 歌词情绪分析
    emotion_bar = Bar()
    emotion_x_data = []
    emotion_y_data = []
    for item in sorted(emotion_list, key=lambda x: x[1], reverse=True)[:20]:
        emotion_x_data.append(item[0])
        emotion_y_data.append(round(item[1], 3))

    emotion_bar.add_xaxis(emotion_x_data)
    emotion_bar.add_yaxis("情绪分值", emotion_y_data)
    emotion_bar.set_global_opts(title_opts=opts.TitleOpts(
        title="歌词情绪好的前20首歌曲"))
    emotion_bar.render("[歌手id-{}]歌词情绪好的前20首歌曲.html".format(singer_id))

    # 作词人统计
    maker_pie = Pie()
    maker_data = []
    for name, times in maker_count.most_common(10):
        maker_data.append((name, times))
    maker_pie.add("出现次数", maker_data)
    maker_pie.set_global_opts(title_opts=opts.TitleOpts(title="合作次数最多的作词人前十名",
                                                        pos_top="8%"),
                              legend_opts=opts.LegendOpts(pos_left="15%"))
    maker_pie.set_series_opts(label_opts=opts.LabelOpts(formatter="{d}%"))
    maker_pie.render("[歌手id-{}]合作次数最多的作词人前十名.html".format(singer_id))

    # 歌词高频词语
    words_bar = Bar()
    word_x_data = []
    word_y_data = []
    for word, count in words_count.most_common(20):
        word_x_data.append(word)
        word_y_data.append(count)

    words_bar.add_xaxis(word_x_data)
    words_bar.add_yaxis("出现次数", word_y_data, category_gap="25%")
    words_bar.set_global_opts(title_opts=opts.TitleOpts(title="歌词中高频出现的前20个词"))
    words_bar.render("[歌手id-{}]歌词中重复出现的前20个词.html".format(singer_id))

    # 评论热门歌曲TOP30
    hot_line = Line()
    x_data = []
    y_data = []
    for song in sorted_songs[:20]:
        x_data.append(db.hget(song[0], "name"))
        y_data.append(song[1])
    hot_line.add_xaxis(x_data)
    hot_line.add_yaxis("评论数", y_data)
    hot_line.set_global_opts(title_opts=opts.TitleOpts(title="评论最火热的前20首歌曲"))
    hot_line.render("[歌手id-{}]热门歌曲TOP20.html".format(singer_id))

    # 评论冷门歌曲TOP30
    # cool_line = Line()
    # x_data = []
    # y_data = []
    # for song in sorted_songs[-20:]:
    #     x_data.append(db.hget(song[0], "name"))
    #     y_data.append(song[1])
    # cool_line.add_xaxis(x_data)
    # cool_line.add_yaxis("评论数", y_data)
    # cool_line.set_global_opts(title_opts=opts.TitleOpts(title="评论冷清歌曲前20首"))
    # cool_line.render("[歌手id-{}]冷门歌曲TOP20.html".format(singer_id))
    return
Beispiel #7
0
from pyecharts.charts import Line

X = [28.9] * 10
n = len(X)
y = []
for i in range(n):
    y.append(i + 1)

bar = Line()
bar.add_xaxis(y)
bar.add_yaxis("thickness", X)
# render 会生成本地 HTML 文件,默认会在当前目录生成 render.html 文件
# 也可以传入路径参数,如 bar.render("mycharts.html")

bar.render()
Beispiel #8
0
        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='/home/aistudio/data/新增确诊趋势图.html')
line.render(path='D:/pycharm/projects/data/新增确诊趋势图.html')
Beispiel #9
0
chart_line_data = data_pld_zh_1.reset_index()
# print(chart_line_data.info())
chart_line_data = chart_line_data.replace(org_dict)
ln = Line(init_opts=opts.InitOpts(
    width='1220px',
    height='760px',
))
ln.add_xaxis(headers)
for row in chart_line_data.index:
    ln.add_yaxis(chart_line_data.iloc[row, 0],
                 chart_line_data.iloc[row, 1:].to_list())
ln.set_global_opts(title_opts=opts.TitleOpts(title="蒙商银行2021年各分行月度存款偏离度情况:"),
                   legend_opts=opts.LegendOpts(orient="vertical",
                                               pos_top="10%",
                                               pos_right="2%"))
ln.render("line_base1.html")
# -----------------------------------    分行偏离度     -----------------------------------
sql_pld_fh = " SELECT I.INDIC_KEY,I.INDIC_NAME,I.ORG_NUM," \
             "CONCAT(YEAR(I.STAT_DT),\'年\',MONTH(I.STAT_DT),\'月\') STAT_DT ," \
             "ROUND(I.IND_VAL,4) IND_VAL " \
         " FROM t09_rm_indic I WHERE 1=1 AND I.CURR_CD = "+p_curr_cd+" AND I.INDIC_KEY = \'YS_JG_164\' " \
         " AND I.PERIOD = \'M\' AND I.STAT_DT >= " + p_stat_dt + " " \
         " AND I.ORG_NUM IN (SELECT O.ORG_NUM FROM t09_report_org O WHERE O.ORG_LEVEL = \'2\' AND O.ORG_TYPE=\'YW\') "
data_pld_fh = pd.read_sql(sql_pld_fh, engine)\
    .rename(columns={'STAT_DT': '月份', 'IND_VAL': '存款偏离度', 'ORG_NUM': '机构'})
data_pld_fh = data_pld_fh.replace(org_dict)

sns.set_theme(style="whitegrid")
ax = sns.stripplot(data=data_pld_fh, x='月份', y='存款偏离度', hue='机构')
plt.rcParams['font.sans-serif'] = ['STXIHEI']
plt.rcParams['axes.unicode_minus'] = False
Beispiel #10
0
                                                     total_latency)
                    print('\n', case_name[:-1], " QPS stddev: ", qps_std_dev,
                          ", latency stddev: ", latency_std_dev)
                else:
                    xx = line.find(".lua")
                    if xx >= 0:
                        case_name = line
                    else:
                        num_thds = line.find("Number of threads: ")
                        if num_thds >= 0:
                            num_threads = str(int(line[num_thds + 18:]))
                print(line)
    finally:
        f.close()

    lp.set_global_opts(
        title_opts=opts.TitleOpts(title="QPS", subtitle="DML only"),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
        toolbox_opts=opts.ToolboxOpts(is_show=True),
        xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False),
    )
    lp.render("sysbench-" + product_name + "-QPS.html")

    lp_latency.set_global_opts(
        title_opts=opts.TitleOpts(title="Latency", subtitle="DML only"),
        tooltip_opts=opts.TooltipOpts(trigger="axis"),
        toolbox_opts=opts.ToolboxOpts(is_show=True),
        xaxis_opts=opts.AxisOpts(type_="category", boundary_gap=False),
    )
    lp_latency.render("sysbench-" + product_name + "-latency.html")
Beispiel #11
0
X = data[['Num', 'x2', 'x4', 'temp']].values
x_train, x_test, train_Y, test_Y = train_test_split(X,Y,\
                            test_size=0.2,random_state=44)
net, scaler_X, scaler_Y = net_eval(data)

y_predict = scaler_Y.inverse_transform(net.predict(\
                             scaler_X.transform(x_test)))
line = Line()

line.add_xaxis(range(1, len(test_Y) + 1))
line.add_yaxis('samples',test_Y.reshape(-1,),\
               label_opts=opts.LabelOpts(is_show=False))
line.add_yaxis('predict',y_predict,\
               label_opts=opts.LabelOpts(is_show=False))
line.set_global_opts(title_opts=opts.TitleOpts(title="line demo"))
line.render('./html/line.html')

# 3D surface
target_feature = (1, 2)
pdp, axes = partial_dependence(net,\
                               scaler_X.transform(x_train),\
                               target_feature,\
                               grid_resolution=30)
XX, YY = np.meshgrid(axes[0], axes[1])
Z = pdp[0].T

names = ['Num', 'x2', 'x4', 'temp']
fig = plt.figure()
ax = Axes3D(fig)
surf = ax.plot_surface(XX,
                       YY,
Beispiel #12
0
                          password='******',
                          database='mydb',
                          charset='utf8')
        cur = conn.cursor()
        sql = "insert into mydb.summary_cony(qz,ys,sw,zy,create_time)\
                     values ({},{},{},{},{});".format(
            '"' + str(getattr(row, 'qz')) + '"',
            '"' + str(getattr(row, 'ys')) + '"',
            '"' + str(getattr(row, 'sw')) + '"',
            '"' + str(getattr(row, 'zy')) + '"',
            '"' + str(getattr(row, 'create_time')) + '"',
        )
        # cur.execute(sql)
        print(sql)
        cur.execute(sql)
        # print(row)
        cur.close()
        # commit 提交
        conn.commit()
        # 关闭MySQL链接
        conn.close()


###画Line
a = Line()
a.add_xaxis(['2019-01-01'])
a.add_yaxis("全国确诊", qg_qz, is_smooth=True)
a.add_yaxis("全国死亡", qg_sw, is_smooth=True)
a.set_global_opts(title_opts=opts.TitleOpts(title="Line-smooth"))
a.render('ceshi.html')
Beispiel #13
0
        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='data/新增确诊趋势图.html')
# 看评论量走势和时间的关系。
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点左右有一个快速增加,达到高峰。后续随着时间的推移,评论人数逐渐减少,趋于平缓。
Beispiel #15
0
        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='/home/aistudio/data/新增确诊趋势图.html')
Beispiel #16
0
# -*- coding: utf-8 -*-
from pyecharts.charts import Line
from requests import get
from time import time
from json import loads
from operator import itemgetter

data = loads(
    get(f"https://view.inews.qq.com/g2/getOnsInfo?name=disease_h5&callback=&_="
        f"{int(time() * 1000)}").json()['data'])["chinaDayList"][-15:]

line = Line()
line.add_xaxis([*map(itemgetter("date"), data)])
line.add_yaxis("确诊", [*map(lambda x: int(x["confirm"]), data)])
line.add_yaxis("疑似", [*map(lambda x: int(x["suspect"]), data)])
line.add_yaxis("治愈", [*map(lambda x: int(x["heal"]), data)])
line.add_yaxis("死亡", [*map(lambda x: int(x["dead"]), data)])
line.render("疫情最新动态.html")
Beispiel #17
0
# 时间排序
time = df_all.日期.value_counts()
time.sort_index(inplace=True)

from pyecharts.charts import Line

# 绘制时间走势图
line1 = Line(init_opts=opts.InitOpts(width='1350px', height='750px'))
line1.add_xaxis(time.index.tolist())
line1.add_yaxis('评论热度',
                time.values.tolist(),
                areastyle_opts=opts.AreaStyleOpts(opacity=0.5),
                label_opts=opts.LabelOpts(is_show=False))
line1.set_global_opts(title_opts=opts.TitleOpts(title="时间走势图"),
                      toolbox_opts=opts.ToolboxOpts())
line1.render('评论时间走势图.html')

# 国内城市top10
city_top10 = df_all.城市处理.value_counts()[:12]
city_top10.drop('国外', inplace=True)
city_top10.drop('未知', inplace=True)

from pyecharts.charts import Bar

# 条形图
bar1 = Bar(init_opts=opts.InitOpts(width='1350px', height='750px'))
bar1.add_xaxis(city_top10.index.tolist())
bar1.add_yaxis("城市", city_top10.values.tolist())
bar1.set_global_opts(title_opts=opts.TitleOpts(title="评论者Top10城市分布"),
                     toolbox_opts=opts.ToolboxOpts())
bar1.render('评论者Top10城市分布条形图.html')
          yaxis3d_opts=opts.Axis3DOpts(Faker.week, type_='category'),
          zaxis3d_opts=opts.Axis3DOpts(type_='value'))
bar3d.set_global_opts(
    visualmap_opts=opts.VisualMapOpts(max_=20),  # 设定最大值边界
    title_opts=opts.TitleOpts(title='Bar3D Sample'))
bar3d.render(path='pyecharts-bar3d.html')

# 折线图,面积图
line = Line()
line.add_xaxis(Faker.choose())
line.add_yaxis('Sample A', Faker.values(), is_smooth=True)
line.add_yaxis('Sample B',
               Faker.values(),
               areastyle_opts=opts.AreaStyleOpts(opacity=0.3, color='blue'))
line.set_global_opts(title_opts=opts.TitleOpts(title='Line Sample'))
line.render(path='pyecharts-line.html')

# 饼图
pie = Pie()
data = [list(z) for z in zip(Faker.choose(), Faker.values())]  # 创建有二个元素列表的列表
pie.add(
    '',
    data,
    radius=['40%', '80%'],  # 内部中空的饼图,指定内环和外环半径
    rosetype='area')  # 通过半径大小区分的玫瑰饼图
pie.set_global_opts(title_opts=opts.TitleOpts(title='Pie Sample'))
pie.set_series_opts(label_opts=opts.LabelOpts(formatter='{b}:{c}'))  # 标签显示格式
pie.render(path='pyecharts-pie.html')

# 特效散点图
effect_scatter = EffectScatter()
Beispiel #19
0
                dataX = []
                dataY = []

                for row in results:
                    # 此处不可以用索引访问:row[0]
                    dataX.append(row["日期"])
                    dataY.append(row["订单量"])
                return dataX, dataY
            except:
                print("错误:数据查询操作失败")
    finally:
        connection.close()


# 执行主函数
if __name__ == '__main__':
    print(order_sum_query())
    dataX, dataY = order_sum_query()
    line = Line()
    line.add_xaxis(dataX)
    line.add_yaxis("订单量", dataY, is_smooth=True)
    line.set_global_opts(title_opts=opts.TitleOpts(title="日订单量历史数据趋势图"),
                         yaxis_opts=opts.AxisOpts(
                             type_="value",
                             axistick_opts=opts.AxisTickOpts(is_show=True),
                             splitline_opts=opts.SplitLineOpts(is_show=True),
                         ),
                         xaxis_opts=opts.AxisOpts(type_="category",
                                                  boundary_gap=False))
    line.render('line.html')
Beispiel #20
0
from pyecharts.charts import Line
from pyecharts.faker import Faker  #虚构的数据
from pyecharts import options as opts  #配置
from pyecharts.charts import Bar  #导入bar图
from pyecharts.globals import ThemeType
import random

line = Line()
line.add_xaxis(Faker.choose())
line.add_yaxis('商家A', Faker.values(), is_smooth=True)
line.add_yaxis('商家B', Faker.values())

line.set_global_opts(
    title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"),
    xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(rotate=30)),  #旋转角度
)

line.render()
Beispiel #21
0
from pyecharts.charts import Line
from pyecharts.faker import Faker
from pyecharts import options as opts

line = Line()

# 设置数据
# 添加x轴,Faker.choose(): 使用faker的随机数据生成x轴标签
line.add_xaxis(Faker.provinces)
# 添加y轴,Faker.values(): 使用faker的随机数据生成y轴数值
line.add_yaxis('数据1', Faker.values())
line.set_global_opts(title_opts=opts.TitleOpts(title='Line 基本示例'))

line.render("line.html")
def query2controller(request):
    # 给定的省份和城市,城市可选,不指定城市的话可以按照省份进行数据筛选
    province, city = '北京', '北京'
    cursor = connection.cursor()
    # 第一步获取时间跨度
    cursor.execute(
        'SELECT MIN("Date") AS "Min", MAX("Date") AS "Max" '
        'FROM "Data"'
    )
    fetchResult = cursor.fetchone();
    minYear, maxYear = int(fetchResult[0][0:4]), int(fetchResult[1][0:4])  # 上一步得到的结果格式为'YYYYMMDD',因此需要将年份提取出来并转换为int
    years = []
    # 建立一个字典,keys预先设置好
    typeDict = {}.fromkeys(('CO', 'NO2', 'O3', 'PM10', 'PM2.5', 'SO2'))
    # 查询每年的数据
    for year in range(minYear, maxYear + 1):
        years.append(str(year))
        curYear = str(year) + '%'
        # 查询粒度为省份
        # cursor.execute(
        #     'SELECT d."Type" AS "Type", ROUND(AVG(d."Value")::NUMERIC, 2) AS "Value" '
        #     'FROM "Data" d, '
        #     '(SELECT m."ID" AS "ID" '
        #     'FROM "Monitors" m, '
        #     '(SELECT c."name" AS "Name" '
        #     'FROM "Provinces" p, "Cities" c '
        #     'WHERE p."name" = %s AND p."province" = c."province") tmptable0 '
        #     'WHERE m."City" = tmptable0."Name") tmptable1 '
        #     'WHERE d."Monitor" = tmptable1."ID" AND d."Date" LIKE %s AND d."Type" <> %s '
        #     'GROUP BY d."Type" ',
        #     [province, curYear, 'AQI']
        # )

        # 查询粒度为城市
        cursor.execute(
            'SELECT d."Type" AS "Type", ROUND(AVG(d."Value")::NUMERIC, 2) AS "Value" '
            'FROM "Data" d, '
            '(SELECT m."ID" AS "ID" '
            'FROM "Monitors" m, '
            '(SELECT c."name" AS "Name" '
            'FROM "Provinces" p, "Cities" c '
            'WHERE p."name" = %s AND p."province" = c."province") tmptable0 '
            'WHERE m."City" = %s) tmptable1 '
            'WHERE d."Monitor" = tmptable1."ID" AND d."Date" LIKE %s AND d."Type" <> %s '
            'GROUP BY d."Type" ',
            [province, city, curYear, 'AQI']
        )
        fetchResult = cursor.fetchall()
        # 对查询结果的数据进行格式转换,因为每一年的查询结果中包含当年的各项指标的值,但是需要的是把各年的所有同类指标放在一起,因此需要在上面建立字典
        for data in fetchResult:
            key, value = data[0], float(data[1])
            if typeDict[key] is None:
                typeDict[key] = [value]
            else:
                typeDict[key].append(value)
    # 创建一个折线图表
    line = Line()
    line.add_xaxis(xaxis_data = years) # 添加横坐标,每个横坐标值的类型必须是str
    # 从字典中提取数据然后添加纵坐标,具体的参数查看官方文档
    for key in typeDict.keys():
        line.add_yaxis(
            series_name = key,
            y_axis = typeDict.get(key),
            label_opts = opts.LabelOpts(is_show = False)
        )
    # 对折线图进行全局设置
    line.set_global_opts(
        title_opts = opts.TitleOpts(title="{}年~{}年{}\n空气质量指数".format(minYear, maxYear, province)), # 如果显示某个城市的数据的话参数中的province改为city
        tooltip_opts = opts.TooltipOpts(trigger = "axis"),
        yaxis_opts = opts.AxisOpts(
            type_ = "value",
            axistick_opts = opts.AxisTickOpts(is_show = True),
            splitline_opts = opts.SplitLineOpts(is_show = True),
        ),
        xaxis_opts = opts.AxisOpts(type_ = "category", boundary_gap = False),
    )
    line.render('templates/line.html') # 将查询结果的图表存为单独的一个html文件
    return render(request, 'HomePage.html') # 在返回的这个html中包含上面的查询结果
def draw_line_with_two_y(xaxis_data, y1_series_name, y1_axis, y2_series_name,
                         y2_axis, y3_series_name, y3_axis, y1_name, y2_name,
                         to_file, unit, svg_name):
    """
    左边是  两条线; 右边是 一条线。
    :param svg_name: svg文件
    :param xaxis_data: 横轴
    :param y1_series_name: 左边第一条线的系列名
    :param y1_axis: 左边第一条线的数值
    :param y2_series_name: 左边第二条线的系列名
    :param y2_axis: 左边第二条线的数值
    :param y3_series_name: 右边第一条线的系列名
    :param y3_axis: 右边第一条线的数值
    :param y1_name: 左边的纵轴名称
    :param y2_name: 右边的纵轴名称
    :param to_file: 结果文件
    :param unit: 横轴的数值的单位(加在每个横轴值后面,比如 月)
    :return:
    """
    xaxis_data = [str(i) + unit for i in xaxis_data]
    bar = Line(init_opts=opts.InitOpts(
        width="800px", height="600px", bg_color='white'
    )).add_xaxis(
        xaxis_data=xaxis_data,
        # add_xaxis=opts.LabelOpts(formatter="{value}" + unit),
    ).add_yaxis(
        series_name=y1_series_name,
        is_smooth=True,
        symbol="circle",
        symbol_size=8,
        is_symbol_show=True,
        # color="#d14a61",
        y_axis=y1_axis,
        yaxis_index=0,
        label_opts=opts.LabelOpts(is_show=False),
        linestyle_opts=opts.LineStyleOpts(width=2),
    ).add_yaxis(
        series_name=y2_series_name,
        is_smooth=True,
        symbol="circle",
        symbol_size=8,
        is_symbol_show=True,
        # color="#d14a61",
        y_axis=y2_axis,
        yaxis_index=0,
        label_opts=opts.LabelOpts(is_show=False),
        linestyle_opts=opts.LineStyleOpts(width=2),
    ).add_yaxis(
        series_name=y3_series_name,
        is_smooth=True,
        symbol="circle",
        symbol_size=8,
        is_symbol_show=True,
        # color="#d14a61",
        y_axis=y3_axis,
        yaxis_index=1,
        label_opts=opts.LabelOpts(is_show=False),
        linestyle_opts=opts.LineStyleOpts(width=2),
    ).extend_axis(yaxis=opts.AxisOpts(
        type_="value",
        name=y2_name,
        # min_=0,
        # max_=25,
        position="right",
        axisline_opts=opts.AxisLineOpts(linestyle_opts=opts.LineStyleOpts()),
        axislabel_opts=opts.LabelOpts(formatter="{value}", font_size=15),
        splitline_opts=opts.SplitLineOpts(
            is_show=True, linestyle_opts=opts.LineStyleOpts(opacity=1)),
        name_textstyle_opts=opts.TextStyleOpts(font_size=15))).set_global_opts(
            yaxis_opts=opts.AxisOpts(
                type_="value",
                name=y1_name,
                # min_=0,
                # max_=250,
                position="left",
                offset=0,
                axisline_opts=opts.AxisLineOpts(
                    linestyle_opts=opts.LineStyleOpts()),
                axislabel_opts=opts.LabelOpts(formatter="{value}",
                                              font_size=15),
                name_textstyle_opts=opts.TextStyleOpts(font_size=15)),
            xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(
                formatter="{value}", font_size=15), ),
            tooltip_opts=opts.TooltipOpts(trigger="axis",
                                          axis_pointer_type="cross"),
            toolbox_opts=opts.ToolboxOpts(feature=opts.ToolBoxFeatureOpts(
                data_zoom=opts.ToolBoxFeatureDataZoomOpts(is_show=False),
                # brush=opts.ToolBoxFeatureBrushOpts(is_show=False),
            )),
            legend_opts=opts.LegendOpts(
                item_width=25,
                item_height=10,
                textstyle_opts=opts.TextStyleOpts(font_size=15)),
        )
    make_snapshot(snapshot, bar.render(to_file), svg_name)  # 生成svg图片
Beispiel #24
0
def handle_time_list(time_list):
    """
    处理float格式的时间数据为 年/月/日 小时:分钟
    time_list: 时间列表
    return: 处理好的时间数据迭代器
    """
    new_time_list = [xlrd.xldate_as_datetime(i, 0).strftime(r'%Y/%m/%d %H:%M') for i in time_list]
    return new_time_list

data = xlrd.open_workbook('C:\\Users\\Administrator\\Desktop\\新建文件夹\\国——月\\12月.xlsx')
table = data.sheets()[0]

PM2_5 = table.col_values(0)
PM10 = table.col_values(1)
CO = table.col_values(2)
NO2 = table.col_values(3)
SO2 = table.col_values(4)
O3 = table.col_values(5)
time = table.col_values(6)


line = Line()
line.add_xaxis(handle_time_list(time[1:]))
line.add_yaxis('PM2.5', PM2_5[1:])
line.add_yaxis('PM10', PM10[1:])
line.add_yaxis('CO', CO[1:])
line.add_yaxis('NO2', NO2[1:])
line.add_yaxis('SO2', SO2[1:])
line.add_yaxis('O3', O3[1:])
line.render('./china/12.html')
# make_snapshot(snapshot, line.render(), 'test.png')
Beispiel #25
0
# -*- encoding: utf-8 -*-

# Project :zs
# Time  :2019/7/22 下午7:32 
# BY    :FormatFa

from pyecharts.charts import Bar,Line


b = Bar()
b.add_xaxis(['one','two','three'])
b.add_yaxis('s1',[1,2,3])


l = Line()
l.add_xaxis(['one','two','three','four'])
l.add_yaxis('s2',[1,2,3])

l.overlap(b)
print(b)
print(l.dump_options())

l.render('test.html')

Beispiel #26
0
        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="新增确诊病例" + today, 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='/Users/liuhui/Desktop/COVID19/html/新增确诊趋势图' + today +
            '.html')
Beispiel #27
0
# 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")

Beispiel #28
0
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/新增确诊趋势图.html')
Beispiel #29
0
x = [e for e in year_com_last['year']]
y = [int(e) for e in year_com_last['mean']]

line = Line()
line.add_xaxis(x)
line.add_yaxis('Delhi', y)

line.set_series_opts(
    markpoint_opts=opts.MarkPointOpts(
        data=[
            opts.MarkPointItem(type_='max', name='最大值'),
            opts.MarkPointItem(type_='min', name='最小值'),
        ]
    ),
    label_opts=opts.LabelOpts(is_show=False),
)

line.set_global_opts(
    title_opts=opts.TitleOpts(
        title='2015-2020印度德里PM2.5年度走势图',
        pos_left='center',
    ),
    legend_opts=opts.LegendOpts(
        pos_left='left',
        orient='vertical',
    )
)

line.render('line_PM2.5_year.html')
    dateAll_info['date'] = dateAll['date']
    dateAll_list.append(dateAll_info)
dateAll_df = pd.DataFrame(dateAll_list)
dateAll_df = dateAll_df.select_dtypes(exclude=['bool'])
dateAll_df.to_csv("g:/sp/国外历史数据.csv")
dateAll_confirm = dateAll_df.confirm.tolist()
dateAll_heal = dateAll_df.heal.tolist()
dateAll_date = dateAll_df.date.tolist()
line = Line()  # 海外疫情历史趋势
x = dateAll_date
y1 = dateAll_confirm
y2 = dateAll_heal
line.add_xaxis(x)
line.add_yaxis('累计确诊', y1)
line.add_yaxis('累计治愈', y2)
line.render("g:/sp/海外疫情历史趋势.html")
# 获取国家名称和数据
print(data_dict['globalStatis'])

areaAll_list = list()
for areaAll in data_dict.get('foreignList'):
    areaAll_info = areaAll
    areaAll_list.append(areaAll_info)
areaAll_df = pd.DataFrame(areaAll_list)
areaAll_df.drop(['children'], axis=1, inplace=True)
areaAll_df.to_csv("g:/sp/国外地区疫情数据.csv")
areaAll_name = areaAll_df.name.tolist()
areaAll_confirm = areaAll_df.confirm.tolist()
areaAll_dead = areaAll_df.dead.tolist()
areaAll_heal = areaAll_df.heal.tolist()