Beispiel #1
0
def printLine(list):
    date = []  #准备一个日期的列表
    startValue = []  #开始的价钱
    endValue = []  #结束的价钱
    for i in range(1, len(list)):
        #把每天的数据录入
        date.append(list[i][1])
        startValue.append(float(list[i][2]))
        endValue.append(float(list[i][5]))

    #设置图片大小
    plt.figure(figsize=(18, 8))  #设置title
    plt.title("沪深300指数2019年全年交易日开盘价收盘价对比")

    ax = plt.gca()  #实例化坐标系
    x_major_locator = MultipleLocator(4)  #设置x轴间隔
    y_major_locator = MultipleLocator(100)  #设置y轴间隔
    ax.xaxis.set_major_locator(x_major_locator)
    ax.yaxis.set_major_locator(y_major_locator)

    plt.xticks(size=9, rotation=90)
    plt.ylim(1500, 3800)  #设置y轴区间

    plt.plot(date, startValue, c='green', label='开盘价')  #开盘价-绿色
    plt.plot(date, endValue, c='blue', label='收盘价')  #收盘价-蓝色
    plt.legend()
    plt.savefig("开盘价与收盘价对比.png", dpi=600)  #保存图片
    plt.show()
Beispiel #2
0
def get_PE_data():
    results1 = PE_data.find({'生产厂家': '上海石化'}).sort("发布时间", pymongo.DESCENDING)
    results2 = PE_data.find({'生产厂家': '扬子石化'}).sort("发布时间", pymongo.DESCENDING)
    count = results1.count()
    s_price = []
    y_price = []
    date = []
    for i in range(count - 1, -1, -1):
        s_price.append(int(results1[i]['价格']))
        y_price.append(int(results2[i]['价格']))
        date.append(results1[i]['发布时间'])
    plt.figure(figsize=(13, 8))
    plt.plot(date, s_price, linewidth=2, color='blue', label="上海石化膜料")
    plt.plot(date, y_price, linewidth=2, color='red', label="扬子石化膜料")
    plt.legend()
    plt.title("中石化PE出厂价格折线图", fontsize=14)
    plt.xlabel("发布时间(年/月/日)", fontsize=14)
    plt.ylabel("价格(元/吨)", fontsize=14)
    ax = plt.gca()
    ax.xaxis.set_major_locator(MultipleLocator(50))
    ax.yaxis.set_major_locator(MultipleLocator(100))
    plt.tick_params(axis='both')
    filename = "中石化PE出厂价格折线图.png"
    plt.savefig(filename)
    plt.show()
    return filename
Beispiel #3
0
def Rt_Ch(stu_act, legends):
    print("legends:", legends)
    lenght_axi = 0.1
    x_major_locator = MultipleLocator(lenght_axi)
    y_major_locator = MultipleLocator(lenght_axi)
    ax = plt.gca()
    ax.xaxis.set_major_locator(x_major_locator)
    ax.yaxis.set_major_locator(y_major_locator)
    plt.xlim(0, 1)
    plt.ylim(0, 1)
    line(0, 0, 0.5, 1)
    line(0.5, 1, 1, 0)
    line(0.3, 0, 0.3, 0.6)
    line(0.7, 0, 0.7, 0.6)
    line(0.3, 0.6, 0.7, 0.6)
    line(0.3, 0.2, 0.7, 0.2)
    rt_list = []
    ch_list = []
    imgurl = "Rt_Ch" + str(int(time.time())) + ".png"
    plt.grid()
    for index in range(len(stu_act)):
        rt, ch = count_Rtch(stu_act[index])
        x = [rt]
        y = [ch]
        rt_list.append(round(rt, 2))
        ch_list.append(round(ch, 2))
        plt.scatter(x, y, label=legends[index], c='k', marker=icon[index])
    plt.xlabel('Rt')
    plt.ylabel('Ch', rotation='horizontal')
    plt.legend()
    plt.savefig("./statics/rt-ch/" + imgurl)
    plt.cla()
    return 'rt-ch/' + imgurl, rt_list, ch_list
Beispiel #4
0
def mutliple_photo(data, space, lenght_axi, duration, grid, label, style):
    x_major_locator = MultipleLocator(lenght_axi)
    y_major_locator = MultipleLocator(lenght_axi)
    ax = plt.gca()
    ax.xaxis.set_major_locator(x_major_locator)
    ax.yaxis.set_major_locator(y_major_locator)
    for index in range(len(data)):
        x, y = str_to_list(data[index], space)
        plt.plot(x,
                 y,
                 color='black',
                 label=label[index],
                 linestyle=style[index])
    if grid == 1:
        plt.grid()
    plt.xlim(0, duration)
    plt.ylim(0, duration)

    plt.xlabel('T')
    plt.ylabel('S', rotation='horizontal')
    plt.legend()
    imgurl = str(int(time.time())) + ".png"
    plt.savefig("./statics/s-t/" + imgurl)
    plt.cla()
    return 's-t/' + imgurl
    def draw(self):
        x=self.pointslist.getallxarraylist()
        y=self.pointslist.getallyarraylist()
        i=0
        colorlist=['red','blue','black']
        ci=0
        for t in self.pointslist.typelist:
            plot1 = plt.plot(self.pointslist.getxarraylistbytype(t), self.pointslist.getyarraylistbytype(t), 's',color=colorlist[ci],label=t)
            plot2 = plt.plot(self.crosspoints[i][0],self.crosspoints[i][1], 's',color='yellow',label='crosspoint')
            plot3 = plt.plot(x,self.yvalsdic[t],'r',color=colorlist[ci],label=t)
            ci=(ci+1)%3
            i+=1
        plot4 = plt.plot(self.weightpoint[0],self.weightpoint[1], 's',label='weightpoint')


        x_major_locator=MultipleLocator(1)
        #把x轴的刻度间隔设置为1,并存在变量里
        y_major_locator=MultipleLocator(1)
        #把y轴的刻度间隔设置为10,并存在变量里
        ax=plt.gca()
        #ax为两条坐标轴的实例
        ax.xaxis.set_major_locator(x_major_locator)
        #把x轴的主刻度设置为1的倍数
        ax.yaxis.set_major_locator(y_major_locator)
        #把y轴的主刻度设置为10的倍数
        plt.xlim(100,150)
        #把x轴的刻度范围设置为-0.5到11,因为0.5不满一个刻度间隔,所以数字不会显示出来,但是能看到一点空白
        plt.ylim(20,30)
        #把y轴的刻度范围设置为-5到110,同理,-5不会标出来,但是能看到一点空白

        plt.legend(loc=4)
        plt.title('algorithm')
        plt.show()
Beispiel #6
0
def plot_pic(x, y, y_locator=0.5, *para):
    #建立图表区
    fig = pl.figure(figsize=(15, 5))
    print('-------------------------------------------------')
    print('{}图正在绘制,请稍后。。。。'.format(para[4]))
    #定义刻度密度
    #根据图片大小自动计算坐标轴密度
    x_locator = int(len(x) / 7)
    x_major_locator = MultipleLocator(x_locator)  #把x轴的刻度间隔设置为默认180分钟,并存在变量里
    y_major_locator = MultipleLocator(y_locator)  #把x轴的刻度间隔设置为0.5,并存在变量里
    ax = pl.gca()
    ax.xaxis.set_major_locator(x_major_locator)  #把x轴的主刻度间隔设置为变量值
    ax.yaxis.set_major_locator(y_major_locator)  #把y轴的主刻度间隔设置为变量值
    #坐标轴标题
    pl.xlabel(para[1])
    pl.ylabel(para[0])
    #坐标轴范围
    pl.ylim(para[2], para[3])
    pl.grid()  #打开网格
    pl.plot(x, y, color='r', linestyle='-')
    #输出
    pl.savefig('./作图/{2}变化_{1}至{0}.jpg'.format(x[-1], x[0], para[4]))
    #简单的交互
    print('完成!')
    print('以下是{0}到{1}时间范围内约{2}小时开机时间的{3}变化曲线:'.format(x[0], x[-1],
                                                      round(len(x) / 60),
                                                      para[4]))
    pl.show()
Beispiel #7
0
 def get_plot_1():
     from matplotlib.pyplot import MultipleLocator
     plt.rcParams['figure.dpi'] = 150
     plt.rcParams['font.sans-serif'] = ['SimHei']
     colour = [
         'r' if q > 0 else 'g' for q in self.annualReturn_dict.values()
     ]
     fig, ax1 = plt.subplots()
     ax1.set_title('年收益率')
     ax1.xaxis.set_major_locator(MultipleLocator(1))
     ax1.bar([str(x) for x in list(self.annualReturn_dict.keys())],
             list(self.annualReturn_dict.values()),
             width=0.5,
             color=colour)
     plt.xticks(rotation=30)
     ax1.set_ylabel('增长率')
     ax2 = ax1.twinx()
     ax2.xaxis.set_major_locator(MultipleLocator(1))
     ax2.plot([str(x) for x in list(self.annualReturn_dict.keys())],
              list(1 +
                   np.cumsum(list(self.annualReturn_dict.values()))),
              color='y',
              linestyle='-.')
     ax2.set_ylabel('净值')
     fig.savefig('D:/work/y.png')
Beispiel #8
0
def draw_pic(observer_position_record):
    plt.figure(figsize=(10, 10))
    #plt.title("[Test case]uav_count=%d, regression_time=%d, bias_max=%d, bias_live_time=%d"%(UAV_BATCH,
    #CONFIG['regression_time'],CONFIG['bias_max'],CONFIG['bias_live_time']))
    plt.title("[Test case]change_step = {:.2f}%".format(CONFIG['change_step'] /
                                                        2 * 100))
    y_range = CONFIG['width'] * CONFIG['grid_size']
    x_range = CONFIG['height'] * CONFIG['grid_size']
    plt.xlim(0, x_range)
    plt.ylim(0, y_range)
    x_major_locator = MultipleLocator(2)
    y_major_locator = MultipleLocator(2)
    ax = plt.gca()
    ax.xaxis.set_major_locator(x_major_locator)
    ax.yaxis.set_major_locator(y_major_locator)
    plt.grid(color='r', linestyle='-', linewidth=1, alpha=0.2)

    for uid, positions in MOVE_RECORD.items():
        for p in positions:
            plt.plot(p[0], p[1], 'o', color='#483D8B')

        for i in range(len(positions) - 1):
            start = (positions[i][0], positions[i + 1][0])
            end = (positions[i][1], positions[i + 1][1])
            plt.plot(start, end, color='#483D8B')
    """
    for p in observer_position_record:
        plt.plot(p[0],p[1],'o',color='#FFA07A')
    
    for i in range(len(observer_position_record)-1):
        start = (observer_position_record[i][0],observer_position_record[i+1][0])
        end = (observer_position_record[i][1],observer_position_record[i+1][1])
        plt.plot(start,end,color='#FFA07A')
    """
    plt.show()
Beispiel #9
0
    def show_env(self):
        # fig = plt.figure()
        ax = plt.subplot()
        plt.xlim((0, self.cols))
        plt.ylim((0, self.rows))
        # name: start, terminal, cliff, barrier, reward, others
        # number: 1, 2, -1, -2, 3, 0
        # color: yellow, orange, gray, black, red, white
        color_dict = {-1: "gray", 1: "yellow",
                      2: "orange", -2: "black", 3: "red", 0: "white"}
        my_x_ticks = np.arange(0, self.cols, 1)
        my_y_ticks = np.arange(0, self.rows, 1)
        plt.xticks(my_x_ticks)
        plt.yticks(my_y_ticks)
        x_major_locator = MultipleLocator(1)
        y_major_locator = MultipleLocator(1)
        ax.xaxis.set_major_locator(x_major_locator)
        ax.yaxis.set_major_locator(y_major_locator)
        ax.xaxis.set_ticks_position('top')
        ax.invert_yaxis()

        plt.grid()
        for i in range(self.rows):
            for j in range(self.cols):
                color = color_dict[int(self.env[i][j])]
                rect = mpathes.Rectangle([j, i], 1, 1, color=color)
                ax.add_patch(rect)
        # plt.savefig('./cliffwalk.jpg')
        plt.show()
Beispiel #10
0
    def dataGrame(self):
        plt.figure(0.5)
        #设置折线图xy坐标主题
        plt.xlabel('time')
        plt.ylabel('memory/K')

        #设置刻度间隔并保存到变量中
        x_major_locator = MultipleLocator(1)
        y_major_locator = MultipleLocator(0.05)
        #实例两条坐标轴
        ax = plt.gca()
        #设置轴的刻度为设置的间隔的倍数
        ax.xaxis.set_major_locator(x_major_locator)
        ax.yaxis.set_major_locator(y_major_locator)

        t_list = []
        result_list = []
        t = 0
        while True:
            t += 1
            t_list.append(t)
            temp = self.getMemory()
            result_list.append(temp)
            plt.plot(t_list,
                     result_list,
                     c='r',
                     ls='-',
                     marker='.',
                     mec='b',
                     mfc='w')  ## 保存历史数据
            # plt.plot(t, np.sin(t), 'o')
            #设置间隔时间(s)
            plt.pause(5)
Beispiel #11
0
def plot_with_labels(low_dim_embs, labels, filename):  # 绘制词向量图
    assert low_dim_embs.shape[0] >= len(labels), 'More labels than embeddings'
    print('绘制向量中......')
    plt.figure(figsize=(10, 10))  # 画布大小
    #plt.xlim(-5, 10)
    # 把x轴的刻度范围设置为-0.5到11
    #plt.ylim(-10, 10)
    # 把y轴的刻度范围设置为-6到10
    for i, label in enumerate(labels):
        x, y = low_dim_embs[i, :]
        plt.scatter(x, y)  # 画点,对应low_dim_embs中每个词向量
        plt.annotate(
            label,  # 显示每个点对应哪个单词
            xy=(x, y),
            xytext=(5, 2),  #文本显示的位置
            textcoords='offset points',
            ha='right',
            va='bottom')
    x_major_locator = MultipleLocator(0.001)
    # 把x轴的刻度间隔设置为1,并存在变量里
    y_major_locator = MultipleLocator(0.001)
    # 把y轴的刻度间隔设置为10,并存在变量里
    #ax = plt.gca()
    # ax为两条坐标轴的实例
    #ax.xaxis.set_major_locator(x_major_locator)
    # 把x轴的主刻度设置为1的倍数
    #ax.yaxis.set_major_locator(y_major_locator)
    # 把y轴的主刻度设置为10的倍数

    plt.savefig(filename)
    plt.show()
Beispiel #12
0
def plot_perf_regression(func_name, res_func_arr):
    perf_picture = plot_dir + str(func_name) + '_perf.png'
    perf_fig_title = str(func_name) + ' Performance Fig'

    # plot
    index1 = list(range(1, len(res_func_arr) + 1))
    index2 = list(range(1, len(res_func_arr) + 1))
    res_mock = numpy.random.rand(len(index2)) * 10 + numpy.mean(res_func_arr)
    plt.figure(figsize=(16, 4))  # picture size
    # plt.plot(index,res_func_arr,color="b--",label="$input_1k$",linewidth=1)
    plt.plot(index1, res_func_arr, label="$10k$", color="blue", linewidth=1)
    plt.plot(index2,
             res_mock,
             label="$110k(Simulated-contrast-test)$",
             color="red",
             linestyle='--',
             linewidth=1)
    plt.xlabel("Version ")  # X label
    plt.ylabel("Cost /ms")  # Y label
    plt.title(perf_fig_title)
    x_major_locator = MultipleLocator(1)
    y_major_locator = MultipleLocator(10)
    ax = plt.gca()
    ax.xaxis.set_major_locator(x_major_locator)
    ax.yaxis.set_major_locator(y_major_locator)
    plt.xlim(0, len(res_func_arr) + 2)
    plt.ylim(min(res_func_arr) - 10, max(res_func_arr) + 10)
    plt.legend()
    # plt.show()
    plt.savefig(perf_picture)
    plt.close('all')
Beispiel #13
0
def AnalyzeClientthroughput(throughput_records0,throughput_records1,duration,str_mpcc_algo,max_thr):
    client_throughput0 = throughput_records0[["timestamp", "throughput"]].values
    client_throughput1 = throughput_records1[["timestamp", "throughput"]].values



    c_s_subflow_1_throughput,=plt.plot(list(client_throughput0[:,0]), list(client_throughput0[:,1]), 'b-') # convert cWnd time unit to millisecond
    c_s_subflow_2_throughput,=plt.plot(list(client_throughput1[:, 0]), list(client_throughput1[:, 1]), 'r-')  # convert cWnd time unit to millisecond

    # print(list(client_throughput0))
    print(list(client_throughput0[0:,1]))
    print("The type of the client_throughput0"+str(type(client_throughput0))+" average:"+str(np.mean(client_throughput0[0:,1])))
    print("The type of the client_throughput1" + str(type(client_throughput1))+" average:"+str(np.mean(client_throughput1[0:,1])))

    plt.legend([c_s_subflow_1_throughput, c_s_subflow_2_throughput], ['subflow 1 cWnd', 'subflow 2 cWnd'], loc='best')
    plt.title('Time-throughput')
    plt.xlabel('Time / s', fontsize = 14, color = 'black')
    plt.ylabel('Kbps', fontsize = 14, color = 'black')
    plt.xlim(0,duration)
    plt.ylim(0,max_thr*1.1)
    x_major_locator=MultipleLocator(10)
    y_major_locator=MultipleLocator(max_thr*1.1/10)
    ax=plt.gca()
    ax.xaxis.set_major_locator(x_major_locator)
    ax.yaxis.set_major_locator(y_major_locator)
Beispiel #14
0
 def set_bg(self):
     plt.cla()
     plt.title(self.game_name)
     plt.grid(linestyle='-')
     plt.axis([-self.margin, self.board.width - self.margin, - self.margin, self.board.height - self.margin])
     x_major_locator=MultipleLocator(1)
     y_major_locator=MultipleLocator(1)
     self.ax.xaxis.set_major_locator(x_major_locator)
     self.ax.yaxis.set_major_locator(y_major_locator)
Beispiel #15
0
def action_plot(data,
                values,
                legend=False,
                ylabel='',
                xaxis='Epoch',
                condition=None):
    assert isinstance(data, pd.DataFrame), 'Data should be a pandas.DataFrame!'
    assert isinstance(values, list), 'Values should be a list!'
    if isinstance(data, list):
        data = pd.concat(data, ignore_index=True)

    data['aer'] *= 5.0
    data['slu'] *= 160.0
    palette = sns.color_palette("mako_r", 6)
    sns.set(style="darkgrid")

    f, ax1 = plt.subplots()
    ax1.set_xlabel('Epoch')
    ax1_major_locator = MultipleLocator(20)
    sns.lineplot(data=data,
                 x=xaxis,
                 y=values[0],
                 linewidth=1,
                 hue=condition,
                 ci='sd',
                 palette=palette)
    ax1.yaxis.set_major_locator(ax1_major_locator)
    plt.ylim(0, 160)

    ax1.set_ylabel('Dosage ($kg/d$)')

    ax2 = ax1.twinx()
    ax2_major_locator = MultipleLocator(0.5)
    sns.lineplot(data=data,
                 x=xaxis,
                 y=values[1],
                 linewidth=1,
                 hue=condition,
                 ci='sd',
                 color='g')
    ax2.yaxis.set_major_locator(ax2_major_locator)
    ax2.set_ylabel('Dissolved oxygen ($mg/L$)')
    plt.ylim(0, 5)
    ax2.grid(False)

    if legend:
        ax1.legend(['Dosage'], loc='best')
        ax2.legend(['Dissolved oxygen'], loc='lower right')

    xscale = np.max(np.asarray(data[xaxis])) > 5e3

    if xscale:
        plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))

    plt.tight_layout(pad=0.5)
    plt.savefig(fname="D:\\rl_wwtp\\parameter.pdf", dpi=300, format="pdf")
    plt.show()
Beispiel #16
0
def plot(traffic_ave_df, PA_daily_ave_df, PA_weekly_ave_df, PA_monthly_ave_df):
    plt.figure(figsize=(40, 40))

    # #plot monthly time series line
    plt.subplot(411)
    plt.plot(traffic_ave_df['time'], traffic_ave_df['traffic_ave'])
    plt.xlim((0, 23))
    x_major_locator = MultipleLocator(1)
    ax = plt.gca()
    ax.xaxis.set_major_locator(x_major_locator)
    plt.grid(True)
    plt.xlabel('hours (h)', fontsize=30)
    plt.ylabel('traffic volume (count)', fontsize=30)
    plt.title('Average traffic volume in an hourly scale in Pennsylvania',
              fontsize=30)

    #plot daily time series line
    plt.subplot(412)
    plt.plot(PA_daily_ave_df['time'], PA_daily_ave_df['traffic_ave'])
    plt.xlim((1, 31))
    x_major_locator = MultipleLocator(1)
    ax = plt.gca()
    ax.xaxis.set_major_locator(x_major_locator)
    plt.grid(True)
    plt.xlabel('daily (d)', fontsize=30)
    plt.ylabel('average traffic volume (count)', fontsize=30)
    plt.title('Average traffic volume in an daily scale in Pennsylvania',
              fontsize=30)

    #plot weekly time series line
    plt.subplot(413)
    plt.plot(PA_weekly_ave_df['time'], PA_weekly_ave_df['traffic_ave'])
    plt.xlim((1, 7))
    x_major_locator = MultipleLocator(1)
    ax = plt.gca()
    ax.xaxis.set_major_locator(x_major_locator)
    plt.grid(True)
    plt.xlabel('week', fontsize=30)
    plt.ylabel('average traffic volume (count)', fontsize=30)
    plt.title('Average traffic volume in an weekly scale in Pennsylvania',
              fontsize=30)

    #plot monthly time series line
    plt.subplot(414)
    plt.plot(PA_monthly_ave_df['time'], PA_monthly_ave_df['traffic_ave'])
    plt.xlim((1, 12))
    x_major_locator = MultipleLocator(1)
    ax = plt.gca()
    ax.xaxis.set_major_locator(x_major_locator)
    plt.grid(True)
    plt.xlabel('month (mo)', fontsize=30)
    plt.ylabel('average traffic volume (count)', fontsize=30)
    plt.title('Average traffic volume in an monthly scale in Pennsylvania',
              fontsize=30)

    plt.savefig('/Users/chenyuyuan/Introduction to Python Prototyping/5.jpg')
Beispiel #17
0
def get_data_BOPET(id):
    product_name = ''
    if id == 1:
        product_name = "12μ印刷膜/镀铝基材"
    elif id == 2:
        product_name = "烫金膜"
    elif id == 3:
        product_name = "厚膜"
    elif id == 4:
        product_name = "转移膜"

    results = BOPET_day.find({
        "date": {
            '$not': {
                '$regex': '^2017'
            }
        }
    }, {"date", "绍兴翔宇." + product_name}).sort("date", pymongo.DESCENDING)
    count = BOPET_day.find({
        "date": {
            '$not': {
                '$regex': '^2017'
            }
        }
    }, {"date", "绍兴翔宇." + product_name}).count()
    statistics_price = []
    statistics_date = []
    for i in range(count - 1, -1, -1):
        data = results[i].get("绍兴翔宇")
        if data:
            if data.get(product_name)['price'] != '':
                try:
                    statistics_price.append(
                        int(data.get(product_name)["price"]))
                except Exception as e:
                    price_str = data.get(product_name)["price"].split("-")
                    price_avg = (int(price_str[0]) + int(price_str[1])) / 2
                    statistics_price.append(price_avg)
                statistics_date.append(results[i].get("date"))
    title = "绍兴翔宇" + product_name + "历史价格变化表"
    price_max = max(statistics_price)
    price_min = min(statistics_price)
    price_interval = (price_max - price_min) / 20
    date_interval = len(statistics_date) / 10
    plt.figure(figsize=(14, 8))
    plt.plot(statistics_date, statistics_price, linewidth=1)
    plt.title(title, fontsize=14)
    plt.xlabel("收盘时间(yyyy-mm-dd)", fontsize=14)
    plt.ylabel("价格(元/吨)", fontsize=14)
    plt.tick_params(axis='both')
    ax = plt.gca()
    ax.xaxis.set_major_locator(MultipleLocator(date_interval))
    ax.yaxis.set_major_locator(MultipleLocator(price_interval))
    plt.savefig(''.join(re.findall(u'[\u4e00-\u9fa5]', title)) + '.png')
    plt.show()
    return ''.join(re.findall(u'[\u4e00-\u9fa5]', title)) + '.png'
    def draw1(self):
        #先画原来的点
        x=self.pointslist.getallxarraylist()
        #x.sort()
        #print ('sort x  ',x)
        y=self.pointslist.getallyarraylist()
        i=0
        colorlist=['red','blue','black']
        ci=0
        xx=[]
        yy=[]


        for i in range(len(self.res.shifted_points)):
            xx.append(self.res.shifted_points[i][0])
            yy.append(self.res.shifted_points[i][1])

        for t in self.pointslist.typelist:
            #print (self.pointslist.getxarraylistbytype(t),self.pointslist.getyarraylistbytype(t))
            plot1 = plt.plot(self.pointslist.getxarraylistbytype(t), self.pointslist.getyarraylistbytype(t), 's',color=colorlist[ci],label=t)
            #print 'resultset'
            #print self.resultSet[t]
            plot1 = plt.plot(self.resultSet[t][0], self.resultSet[t][1], 's',color=colorlist[ci+1],label='density center')
            #print ('this set:',self.resultSet[t][1], self.resultSet[t][1] )
            #plot1=plt.plot(xx,yy, 's',color=colorlist[ci+2],label='miduzhongxins')
            #plot2 = plt.plot(self.crosspoints[i][0],self.crosspoints[i][1], 's',color='yellow',label='crosspoint')
            plot3 = plt.plot(x,self.yvalsdic[t],'r',color=colorlist[ci],label=t)
            #x.sort()
            #print x
            #print 'xxx'
            ci=(ci+1)%3
            i+=1
        #plot4 = plt.plot(self.weightpoint[0],self.weightpoint[1], 's',label='weightpoint')
        x_major_locator=MultipleLocator(1)
        #把x轴的刻度间隔设置为1,并存在变量里
        y_major_locator=MultipleLocator(1)
        #把y轴的刻度间隔设置为10,并存在变量里
        ax=plt.gca()
        #ax为两条坐标轴的实例
        ax.xaxis.set_major_locator(x_major_locator)
        #把x轴的主刻度设置为1的倍数
        ax.yaxis.set_major_locator(y_major_locator)
        #把y轴的主刻度设置为10的倍数
        plt.xlim(100,150)
        #把x轴的刻度范围设置为-0.5到11,因为0.5不满一个刻度间隔,所以数字不会显示出来,但是能看到一点空白
        plt.ylim(20,30)
        #把y轴的刻度范围设置为-5到110,同理,-5不会标出来,但是能看到一点空白




        plt.legend(loc=4)
        plt.title('algorithm')
        plt.show()
        pass
def BGRHistogramCurve(img_bgr, amount_gray_level=256):

    img_gray = img_bgr[:, :, 0]

    #for frequency calculation
    pixel_amount = len(list(img_gray.ravel()))

    #step between gray level nearby
    step_gray_level = int(np.ceil(256 / amount_gray_level))
    '''plot BGR histogram'''
    fig, ax = plt.subplots(figsize=(10, 6))
    colors = ('b', 'g', 'r')

    #3 channels
    for i, col in enumerate(colors):

        this_histogram = []

        this_hist = cv2.calcHist([img_bgr], [i], None, [amount_gray_level],
                                 [0, 256])

        for frequency_this_level in this_hist:

            this_histogram += [
                frequency_this_level / step_gray_level / pixel_amount
            ] * step_gray_level

        plt.plot(this_histogram, color=col, label=col.upper())
        plt.legend(prop=legend_font)
        plt.xlim([0, 256])

    #set ticks
    plt.tick_params(labelsize=12)
    labels = ax.get_xticklabels() + ax.get_yticklabels()

    #label fonts
    [this_label.set_fontname('Times New Roman') for this_label in labels]

    plt.title('BGR Histogram', FontProperties=title_font)

    plt.xlabel('BGR Level', FontProperties=annotation_font)
    plt.ylabel('Frequency', FontProperties=annotation_font)

    #tick step
    x_major_step = 16
    x_minor_step = 8
    y_major_step = (max(this_histogram) - min(this_histogram)) / 10
    y_minor_step = (max(this_histogram) - min(this_histogram)) / 20

    #set locator
    ax.xaxis.set_major_locator(MultipleLocator(x_major_step))
    ax.xaxis.set_minor_locator(MultipleLocator(x_minor_step))
    ax.yaxis.set_major_locator(MultipleLocator(y_major_step))
    ax.yaxis.set_minor_locator(MultipleLocator(y_minor_step))
Beispiel #20
0
def plot2dcomp4(data1, data2, data3, data4, x10, x20, x30, x40,
                dt, steps, lw=1.0, ti="Plot", fn="test2d.pdf", sa=True):
    x1, y1, z1 = data1[:, 0], data1[:, 1], data1[:, 2]
    x2, y2, z2 = data2[:, 0], data2[:, 1], data2[:, 2]
    x3, y3, z3 = data3[:, 0], data3[:, 1], data3[:, 2]
    x4, y4, z4 = data4[:, 0], data4[:, 1], data4[:, 2]

    t = np.linspace(0, steps * dt, steps)
    plt.figure()
    plt.subplot(311)  # plot x-t
    plt.title(ti)
    plt.plot(t, x1, color='red', linewidth=lw, label=str(x10))
    plt.plot(t, x2, color='blue', linewidth=lw, label=str(x20))
    plt.plot(t, x3, color='green', linewidth=lw, label=str(x30))
    plt.plot(t, x4, color='black', linewidth=lw, label=str(x40))
    plt.legend(loc="upper right", fontsize=8, ncol=4)
    plt.ylabel('x')
    ax = plt.gca()
    ax.set_xticklabels([])
    ax.yaxis.set_major_locator(MultipleLocator(10))
    ax.tick_params(axis='y', labelsize=8)
    ax.set_xlim(0, steps * dt)

    plt.subplot(312)  # plot y-t
    plt.plot(t, y1, color='red', linewidth=lw, label=str(x10))
    plt.plot(t, y2, color='blue', linewidth=lw, label=str(x20))
    plt.plot(t, y3, color='green', linewidth=lw, label=str(x30))
    plt.plot(t, y4, color='black', linewidth=lw, label=str(x40))
    plt.ylabel('y')
    ax = plt.gca()
    ax.set_xticklabels([])
    ax.yaxis.set_major_locator(MultipleLocator(10))
    ax.tick_params(axis='y', labelsize=8)
    ax.set_xlim(0, steps * dt)

    plt.subplot(313)  # plot z-t
    plt.plot(t, z1, color='red', linewidth=lw, label=str(x10))
    plt.plot(t, z2, color='blue', linewidth=lw, label=str(x20))
    plt.plot(t, z3, color='green', linewidth=lw, label=str(x30))
    plt.plot(t, z4, color='black', linewidth=lw, label=str(x40))
    plt.xlabel('t')
    plt.ylabel('z')
    ax = plt.gca()
    ax.yaxis.set_major_locator(MultipleLocator(10))
    ax.tick_params(axis='y', labelsize=8)
    ax.tick_params(axis='x', labelsize=8)
    ax.set_xlim(0, steps * dt)
    plt.tight_layout()

    if sa:
        plt.savefig(fn)
    plt.show()
    plt.close()
Beispiel #21
0
def picture(d_s, epoch):
    plt.figure(figsize=(12, 6))  # 创建绘图对象
    x = []
    y = []
    average_s = []
    average_acc = []
    for d in d_s:
        average = 0
        acc = 0
        for i in range(epoch):
            Accuracy, Precision, Recall, F_Score = Model(d)
            x.append(d)
            y.append(F_Score)
            acc += Accuracy
            average += F_Score
        average /= epoch
        acc /= epoch
        average_acc.append(acc)
        average_s.append(average)
    plt.plot(x, y, color='c', marker='o', markersize=2, linewidth=0)
    plt.plot(d_s,
             average_s,
             color='c',
             marker='o',
             linestyle='--',
             markersize=3,
             linewidth=1,
             label='average F_Score')
    for a, b in zip(d_s, average_s):
        plt.text(a, b, (b), ha='left', va='bottom', fontsize=9)
    plt.plot(d_s,
             average_acc,
             color='g',
             marker='o',
             linestyle='-.',
             markersize=3,
             linewidth=1,
             label='average Accuarcy')
    for a, b in zip(d_s, average_acc):
        plt.text(a, b, (b), ha='left', va='bottom', fontsize=9)

    x_major_locator = MultipleLocator(2)
    y_major_locator = MultipleLocator(0.1)
    ax = plt.gca()  # ax为两条坐标轴的实例
    ax.xaxis.set_major_locator(x_major_locator)  # x轴的主刻度设置
    ax.yaxis.set_major_locator(y_major_locator)  # y轴的主刻度设置
    plt.xlim(5, 17)
    plt.ylim(-0.05, 1.05)
    plt.xlabel("feature_d", fontsize='15')  # X轴标签
    plt.ylabel("F_Score", fontsize='15')  # Y轴标签
    plt.legend(fontsize='15', loc="upper right")
    plt.savefig("data/d_FScore_Accuracy.png")  #保存图
    plt.show()  # 显示图
Beispiel #22
0
def main():
    metadata, data = parse_xpm(sys.argv[1])
    x, y, z = map(np.asarray, data)
    #x, y = np.meshgrid(x, y)
    font = {'family': 'Times New Roman',
            'weight': 'regular',
            'size': '12'}
    plt.rc('font', **font)
    x_major = MultipleLocator(500)
    y_major = MultipleLocator(20)
    colors = [(1, 1, 1), (1, 0, 0), (0, 0, 0), (0, 1, 0), 
              (1, 1, 0), (0, 0, 1), (0.7, 0.3, 0.8), (0.5, 0.5, 0.5)]
    cmap_name = 'my_list'
    cm = LinearSegmentedColormap.from_list(cmap_name, colors, N=8)
    plt.figure(figsize=(6, 6))
    ax = plt.gca()
    ax.xaxis.set_major_locator(x_major)
    ax.yaxis.set_major_locator(y_major)
    
    plt.imshow(z, cmap=cm, origin='upper')
    xtick_list = map(int, ax.get_xticks().tolist())
    ori_xticks = [xt for xt in xtick_list if xt>=0 and xt<=len(data[0])]
    for itick, xtick in enumerate(xtick_list[:]):
        if xtick >= 0 and xtick <= len(data[0]):
            xtick_list[itick] = data[0][xtick]
    ax.set_xticklabels(xtick_list)
    
    ytick_list = map(int, ax.get_yticks().tolist())
    ori_yticks = [xt for xt in ytick_list if xt>=0 and xt<=len(data[1])]
    ymin, ymax = ax.get_ylim()
    n_y_ticks = len(ori_yticks)
    y_spacing = ori_yticks[1] - ori_yticks[0]
    y_tick_list = [ymin - y_spacing*t for t in range(n_y_ticks)]
    y_tick_list = map(int, y_tick_list)
    y_labels = [data[1][ytick] for ytick in y_tick_list][::-1]
    offset = max(y_labels) - max(ytick_list)
    y_labels = [ytick - offset for ytick in y_labels]
    y_labels = map(int, y_labels)
    
    ax.set_yticks(y_tick_list)
    ax.set_yticklabels(y_labels)
    
    plt.xlabel(metadata.get('x-label', ''))
    plt.ylabel(metadata.get('y-label', ''))
    plt.title(metadata.get('title', ''))
    
    divider = make_axes_locatable(ax)
    cax = divider.append_axes("right", size="5%", pad=0.05)
    cb = plt.colorbar(cax=cax)
    cb.set_ticks(range(0, 8))
    cb.set_ticklabels(['Coil', 'B-Sheet', 'B-Bridge', 'Bend', 'Turn', 'A-Helix', '5-Helix', '3-Helix'])
    plt.savefig("ss.pdf", dpi = 600)
    plt.show()
Beispiel #23
0
def plotCurve(data, label, w_list, cost_list, mode):
	"""
	plot the boundary and cost curve.

	Args:
		data(List):
		label(List):
		w_list(List): the recorded weights. Element Type: np.matrix
		cost_list(List): the recorded costs.  Element Type: float

	Return:
	"""
	dataMat, fs = normalize(data); labelMat= np.mat(label).T
	m, n = np.shape(dataMat)
	xcord1 = []; ycord1 = []
	xcord2 = []; ycord2 = []
	for i in range(m):
		if labelMat[i,0] == 1.:
			xcord1.append(dataMat[i,1]); ycord1.append(dataMat[i,2])
		else:
			xcord2.append(dataMat[i,1]); ycord2.append(dataMat[i,2])
	plt.ion()
	ax1 = plt.subplot(1, 2, 1);ax2 = plt.subplot(1, 2, 2)
	ax1.set_title('Boundary');ax1.set_xlim(15, 65);ax1.set_ylim(40, 90)
	ax1.set_xlabel('exam1 score'); ax1.set_ylabel('exam2 score')
	ax1.plot(np.array(xcord1)*fs[1] + fs[0], np.array(ycord1)*fs[3]+fs[2], 'g+', markersize=6,label='Admitted')
	ax1.plot(np.array(xcord2)*fs[1] + fs[0], np.array(ycord2)*fs[3]+fs[2], 'ro', markersize=6, label='Not Admitted')
	ax1.legend(loc='upper left')
	ax1.xaxis.set_major_locator(MultipleLocator(5)); ax1.yaxis.set_major_locator(MultipleLocator(5))
	x_line = np.linspace(-0.5, 1.5, 400)

	ax2.set_title('Cost'); ax2.set_ylim(min(cost_list)*0.95, max(cost_list)*1.01)
	ax2.set_xlabel('Iteration /50') if mode == 'GD' else ax2.set_xlabel('Iteration / 100')
	ax2.set_ylabel('Cost')
	xcord_ax2 = []; ycord_ax2 = []
	for i in range(len(w_list)):
		plt.pause(0.2)
		ax2.set_xlim(-1, i);xcord_ax2.append(i);ycord_ax2.append(cost_list[i])
		ax2.scatter(i, cost_list[i], c='r', marker='o')
		try:
			ax1.lines.remove(line_ax1[0])
			ax2.lines.remove(line_ax2[0])
		except:
			pass
		cur_w = w_list[i]
		y_line = (- cur_w[0,0] - cur_w[1,0] * x_line) / cur_w[2,0]
		line_ax1 = ax1.plot(x_line*fs[1]+fs[0], y_line*fs[3]+fs[2], c='black')
		line_ax2 = ax2.plot(xcord_ax2, ycord_ax2)

	plt.ioff()
	plt.show()
	return
Beispiel #24
0
 def GET(self, attempt_id):
     jobid = get_jobid_by_attempid(attempt_id)
     job = all.get(jobid)
     if not job:
         return web.notfound
     attempt = job.attempts.get(attempt_id)
     if not attempt:
         return web.notfound
     exes = attempt.exes
     fig = plt.figure(figsize=(15, 10))
     #内存图
     ax = fig.add_subplot(211)
     for exe in exes.itervalues():
         pn = "%s(%s)" % (exe.exe, exe.id)
         ax.plot([time_to_string(x[0]) for x in exe.seqs['r'].vs],
                 [x[1] for x in exe.seqs['r'].vs],
                 'm.-',
                 label=pn + ' RSS',
                 linewidth=1)
     # 设置y轴范围
     plt.ylim(0, 1024)
     #坐标轴朝内
     plt.rcParams['xtick.direction'] = 'in'
     plt.rcParams['ytick.direction'] = 'in'
     #设置坐标轴名称
     plt.xlabel('RSS(MB)')
     plt.ylabel('Time')
     x_major_locator = MultipleLocator(10)
     ax.xaxis.set_major_locator(x_major_locator)
     ax.legend()  #添加图例
     #CPU图
     ax2 = fig.add_subplot(212)
     for exe in exes.itervalues():
         pn = "%s(%s)" % (exe.exe, exe.id)
         ax2.plot([time_to_string(x[0]) for x in exe.seqs['c'].vs],
                  [x[1] for x in exe.seqs['c'].vs],
                  'm.-',
                  label=pn + ' CPU',
                  linewidth=1)
     plt.ylim(-5, 150)
     plt.rcParams['xtick.direction'] = 'in'
     plt.rcParams['ytick.direction'] = 'in'
     # 设置坐标轴名称
     plt.xlabel('CPU')
     plt.ylabel('Time')
     x_major_locator = MultipleLocator(10)
     ax2.xaxis.set_major_locator(x_major_locator)
     ax2.legend()
     web.header("Content-Type", "image/png")
     buff = StringIO.StringIO()
     fig.savefig(buff, format='png')
     return buff.getvalue()
Beispiel #25
0
def draw_degree(G):
    degree_sequence = sorted([d for n, d in G.degree()],
                             reverse=True)  # degree sequence
    degreeCount = collections.Counter(degree_sequence)
    deg, cnt = zip(*degreeCount.items())

    degree = nx.degree_histogram(G)
    x = range(len(degree))
    y = [z / float(sum(degree)) for z in degree]

    # fig = plt.figure()
    fig, ax1 = plt.subplots()
    # plt.bar([d for d in deg], cnt, width=0.50, color="b",label='wwww')

    plt.title("Degree Distribution of OGB-arxiv", fontsize='xx-large')

    # bar graph
    ax1.bar([d for d in deg],
            cnt,
            width=0.50,
            color="b",
            label="Number of nodes in degree distribution")
    ax1.set_ylabel("Count")
    ax1.set_xlabel("Degree")
    x_minor_locator_ax1 = MultipleLocator(2)
    y_minor_locator_ax1 = MultipleLocator(500)
    ax1.xaxis.set_minor_locator(x_minor_locator_ax1)
    ax1.yaxis.set_minor_locator(y_minor_locator_ax1)
    ax1.set_xticks([d * 20 for d in range(0, 50)])
    ax1.set_xticklabels([d * 20 for d in range(0, 50)])

    ax2 = ax1.twinx()

    # plot graph
    ax2.plot(x, y, 'r', label="Degree distribution probability")
    ax2.set_ylabel('Probability')
    y_minor_locator_ax2 = MultipleLocator(0.01)
    ax2.yaxis.set_minor_locator(y_minor_locator_ax2)
    ax2.set_ylim(-0.01, 0.3)

    # Legend location
    ax1.legend(bbox_to_anchor=(1, 0.98))
    ax2.legend(bbox_to_anchor=(1, 0.88))

    # X-axis limit
    plt.xlim(-5, 250)

    #plt.text(150,0.35,'Number of nodes:10000')
    #plt.text(150,0.3,'Number of blocks:2')

    plt.savefig('picture.png')
    plt.show()
Beispiel #26
0
def plotCurve(data, label, x_grid, g_list, cost_list, mode):
	"""
	plot the boundary and cost curve.

	Args:
		data(List):
		label(List):
		x_grid(List): contour for ploting.
		g_list(List): the recorded contours.
		cost_list(List): the recorded costs.  Element Type: float

	Return:
	"""
	dataMat, fs = normalize(data); labelMat= np.mat(label).T
	m, n = np.shape(dataMat)
	xcord1 = []; ycord1 = []
	xcord2 = []; ycord2 = []
	for i in range(m):
		if labelMat[i,0] == 1.:
			xcord1.append(dataMat[i,1]); ycord1.append(dataMat[i,2])
		else:
			xcord2.append(dataMat[i,1]); ycord2.append(dataMat[i,2])
	plt.ion()
	ax1 = plt.subplot(1, 2, 1);ax2 = plt.subplot(1, 2, 2)
	ax1.set_title('Boundary');ax1.set_xlim(15, 65);ax1.set_ylim(40, 90)
	ax1.set_xlabel('exam1 score'); ax1.set_ylabel('exam2 score')
	#use plot instead of scatter due to ax.contourf is able to cover scatter dots.
	ax1.plot(np.array(xcord1) * fs[1] + fs[0], np.array(ycord1) * fs[3] + fs[2], 'g+', markersize=6,label='Admitted')
	ax1.plot(np.array(xcord2) * fs[1] + fs[0], np.array(ycord2) * fs[2] + fs[3], 'ro', markersize=6, label='Not Admitted')
	ax1.legend(loc='upper left')
	ax1.xaxis.set_major_locator(MultipleLocator(5)); ax1.yaxis.set_major_locator(MultipleLocator(5))
	custom_cmap = ListedColormap(['#fafab0','#a0faa0'])#'#9898ff'])

	ax2.set_title('Cost'); ax2.set_ylim(min(cost_list)*0.95, max(cost_list) * 1.01)
	ax2.set_xlabel('Iteration /50') if mode=='GD' else ax2.set_xlabel('Iteration /100') 
	ax2.set_ylabel('Cost')
	xcord_ax2 = []; ycord_ax2 = []
	for i in range(len(g_list)):
		plt.pause(0.2)
		ax2.set_xlim(-1, i);xcord_ax2.append(i);ycord_ax2.append(cost_list[i])
		ax2.scatter(i, cost_list[i], c='r', marker='o')
		try:
			ax2.lines.remove(line_ax2[0])
		except:
			pass
		ax1.contourf(x_grid[0] , x_grid[1], g_list[i], cmap=custom_cmap)
		line_ax2 = ax2.plot(xcord_ax2, ycord_ax2)

	plt.ioff()
	plt.show()
	return
Beispiel #27
0
    def png_after_review(self):
        #if date_str in day_ls:

        day_count_ls[day_ls.index(date_str)] = str(
            eval(day_count_ls[day_ls.index(date_str)]) + today_count)

        #else:
        #    day_ls.append(date_str)
        #    day_count_ls.append(str(today_count))

        today_task.update_data()

        day_count_ls_eval = list(map(int, day_count_ls))
        day_max = int(date_str[-2:])
        count_max = max(day_count_ls_eval)

        def cut_day(day):
            if day[-2] == '0':
                return day[-1]
            else:
                return day[-2:]

        day_ls_cut = list(map(cut_day, day_ls))
        # print(day_count_ls)
        # print(day_count_ls_eval)

        #plt.title("有效复习单词个数统计图", fontsize=fs)
        x_label = today_task.month
        table = x_label + " 有效复习单词个数统计图"
        plt.axis([-1, day_max, -1, count_max + 1])

        x_major_locator = MultipleLocator(1)
        y_major_locator = MultipleLocator(1)
        ax = plt.gca()
        # ax为两条坐标轴的实例
        ax.xaxis.set_major_locator(x_major_locator)
        # 把x轴的主刻度设置为1的倍数
        ax.yaxis.set_major_locator(y_major_locator)
        # 把y轴的主刻度设置为1的倍数

        plt.xlabel(table, fontproperties='SimHei', fontsize=12)
        #plt.xlabel(x_label, fontproperties='SimHei', fontsize=12)
        #plt.ylabel('当日有效复习单词个数', fontsize=12)
        plt.plot(day_ls_cut, day_count_ls_eval, 'ob--')
        plt.grid(True)

        #plt.figure(figsize=(2, 1))  # 图像大小

        name = '统计图\\' + date_str[:7] + '.png'
        plt.savefig(name, dpi=600)  # 生成PNG文件
Beispiel #28
0
def get_data_CPP(product):
    results = CPP_data.find({}, {product, "datetime"}).sort(
        "datetime", pymongo.DESCENDING)
    count = CPP_data.find({}, {product, "datetime"}).count()
    statistics_price1 = []
    statistics_price2 = []
    statistics_price3 = []
    statistics_date = []
    for i in range(count - 1, -1, -1):
        data = results[i].get(product)
        if data:
            statistics_price1.append(int(data.get("华北地区")["价格"]))
            statistics_price2.append(int(data.get("华东地区")["价格"]))
            if data.get("华南地区"):
                statistics_price3.append(int(data.get("华南地区")["价格"]))
            statistics_date.append(results[i].get("datetime"))
    plt.figure(figsize=(11, 8))
    line1, = plt.plot(statistics_date,
                      statistics_price1,
                      linewidth=2,
                      label="华北地区")
    line2, = plt.plot(statistics_date,
                      statistics_price2,
                      linewidth=2,
                      label="华东地区")
    if not statistics_price3:
        plt.legend(handles=[line1, line2], labels=["华北地区", "华东地区"])
    else:
        line3, = plt.plot(statistics_date,
                          statistics_price3,
                          linewidth=2,
                          label="华南地区")
        plt.legend(handles=[
            line1,
            line2,
            line3,
        ],
                   labels=["华北地区", "华东地区", "华南地区"])

    plt.title("国内" + product + "出厂收盘价格变化表", fontsize=14)
    plt.xlabel("收盘时间(yyyy-mm-dd)", fontsize=14)
    plt.ylabel("价格(元/吨)", fontsize=14)
    plt.tick_params(axis='both')
    ax = plt.gca()
    ax.xaxis.set_major_locator(MultipleLocator(25))
    ax.yaxis.set_major_locator(MultipleLocator(100))
    filename = "国内" + product + "出厂收盘价格变化表.png"
    plt.savefig(filename)
    plt.show()
    return filename
Beispiel #29
0
def show(x, y, title):
    from matplotlib import pyplot as plt
    from matplotlib.pyplot import MultipleLocator
    x_major_locator = MultipleLocator(x_interval)
    y_major_locator = MultipleLocator(y_interval)
    ax = plt.gca()
    ax.xaxis.set_major_locator(x_major_locator)
    ax.yaxis.set_major_locator(y_major_locator)
    plt.title(title)
    plt.grid()
    plt.plot(x, y)
    plt.savefig(f"analys_{title}.jpg")
    plt.show()
    plt.close()
Beispiel #30
0
def jt(jj):
    com = create_engine("mysql+pymysql://root:root@localhost:3306/sx")
    s = "select  city,COUNT(DISTINCT jobtype) as sumnumber from {}  group by city"
    sql = s.format(jj)
    df = pd.read_sql_query(sql, com)
    if jj == "Rjob":
        j = "人工智能"
    elif jj == "Djob":
        j = "大数据"
    elif jj == "Jjob":
        j = "嵌入式"
    elif jj == "Pjob":
        j = "Python"
    mp.rcParams["font.family"] = "Microsoft YaHei"  # 默认 sans-serif
    mp.rcParams["font.size"] = 15  # 默认10
    clist = df["city"]  # 定义两个列表
    nlist = df["sumnumber"]
    x = []
    y = []
    d = dict(zip(clist, nlist))
    list = sorted(d.items(), key=lambda kv: (kv[1], kv[0]), reverse=True)  # 得到的是一个list,list中的元素是tuple
    for i in list:
        x.append(i[0])  # 把元组中的第一个值添加到x中
        y.append(i[1])  # 把元组中的第二个值添加到y中
    plt.figure(figsize=(20, 12), facecolor="#F1F5FB", dpi=80)
    plt.bar(x, y, color='lightsteelblue', width=0.5)
    plt.xlabel("城市", fontsize=14)
    plt.ylabel("需求职位数", fontsize=14)
    x_major_locator = MultipleLocator(1)  # 把x轴的刻度间隔设置为1,并存在变量里
    y_major_locator = MultipleLocator(10)  # 把y轴的刻度间隔设置为10,并存在变量里
    ax = plt.gca()
    # ax为两条坐标轴的实例
    ax.xaxis.set_major_locator(x_major_locator)
    # 把x轴的主刻度设置为1的倍数
    ax.yaxis.set_major_locator(y_major_locator)
    # 把y轴的主刻度设置为10的倍数
    plt.xlim(-0.5, len(x))
    # 把x轴的刻度范围设置为-0.5到11,因为0.5不满一个刻度间隔,所以数字不会显示出来,但是能看到一点空白
    plt.ylim(0, max(y) + 10)
    # 把y轴的刻度范围设置为0到70,同理,-5不会标出来,但是能看到一点空白
    plt.xticks(rotation=90)

    temp = zip(x, y)
    for x, y in temp:
        plt.text(x, y + 1, y, ha="center", va="top")

    plt.title("{}各个城市需求的职位数".format(j), fontsize=14)
    plt.savefig("city_jt.png")
    return plt