def time_distribution(self, doc):
     doc = self.loc
     # startTime = pd.Timestamp(self.tableName[0:8] + "0:00")
     startTime = datetime.strptime(self.tableName[0:8] + " 8:00",
                                   "%Y%m%d %H:%M")
     dates = pd.date_range(start=startTime, periods=24, freq="1H")
     time_dis = pd.DataFrame(0, index=dates, columns=["tweets"])
     timeList = []
     for tweet in doc:
         t_time = datetime.strptime(tweet[0], "%Y年%m月%d日 %H:%M")
         timeList.append(t_time)
     for time in timeList:
         for j in time_dis.index:
             if time.hour < j.hour + 1 and time.day == j.day:
                 # if time.minute < j.minute+10 and time.day == j.day and time.hour == j.hour:
                 time_dis.loc[j, ['tweets']] += 1
                 break
     matplotlib.matplotlib_fname()
     dfplt = time_dis.plot(kind="bar")
     plt.title(self.tableName, fontproperties=font)
     plt.xlabel("Time")
     plt.ylabel("tweers")
     plt.subplots_adjust(bottom=0.4)
     savefig("C:/Users/97272/Desktop/output/" + str(self.tableName) +
             ".png")
     plt.show()
示例#2
0
    def time_analy(self):
        cf = ClientFilter()
        dates = pd.date_range(start=self.table_name[0:11] + " 0:00",
                              periods=48,
                              freq="1H")
        df = pd.DataFrame(0, index=dates, columns=['tweets'])
        tweet_times = []
        for raw in self.col.find():
            if cf.check(raw['user_name']):
                t_time = datetime.strptime(
                    self.table_name[0:4] + "年" + raw['time'],
                    "%Y年%m月%d日 %H:%M")
                tweet_times.append(t_time)
        for i in tweet_times:
            for j in df.index:
                if i.hour < j.hour + 1 and i.day == j.day:
                    df.loc[j, ['tweets']] += 1
                    break
        matplotlib.matplotlib_fname()
        #print(df)
        dfplt = df.plot(kind='bar', title=self.table_name)

        plt.xlabel("time")
        plt.ylabel("tweets")
        plt.show()
示例#3
0
def main():
    '''
        Process to create an animiated graphic using FuncAnimation (from http://www.acme.byu.edu/wp-content/uploads/2018/09/Animation.pdf)
        1. Compute all data to be plotted.
        2. Explicitly define figure object.
        3. Define line objects to be altered dynamically.
        4. Create function to update line objects.
        5. Create FuncAnimation object.
        6. Display using plt.show().
        
        Approach from the following sources:
        https://stackoverflow.com/questions/45712099/updating-z-data-on-a-surface-plot-in-matplotlib-animation
        https://pythonmatplotlibtips.blogspot.com/2018/11/animation-3d-surface-plot-artistanimation-matplotlib.html
    '''
    s = -0.20
    T = 100
    N = 200
    L = 200
    Nx = 10
    Ny = 10
    Nt = 10
    dt = T/Nt
    dx = N/Nx
    dy = L/Ny    
    debug = False
    matplotlib.matplotlib_fname()

    #1. Compute all data to be plotted.
    #2. Explicitly define figure object.
    r = HeatOnRectangle(N, L, T, dx, dy, dt, T, debug)
    r.applyInitialConditionsAnim()
    r.calcDataAnimation(T)
    #print (r.uAnimation)
    
    X, Y = np.meshgrid(r.x,r.y)
    
    # Plot the surface.
    plot = [r.ax.plot_surface(X, Y, r.uAnimation[:,:,0], cmap=cm.coolwarm, linewidth=0, antialiased=False)]
    
    # Add a color bar which maps values to colors.
    #r.fig.colorbar(plot, shrink=0.5, aspect=5)

    # call the animator.  blit=True means only re-draw the parts that have changed.
    ani = animation.FuncAnimation(r.fig, r.animatePlot, T, fargs=(X,Y,plot), interval=100, blit=False)
    
    # save the animation as an mp4.  This requires ffmpeg or mencoder to be
    # installed.  The extra_args ensure that the x264 codec is used, so that
    # the video can be embedded in html5.  You may need to adjust this for
    # your system: for more information, see
    # http://matplotlib.sourceforge.net/api/animation_api.html
    #ani.save('basic_animation.mp4', fps=30)
   
    plt.show()

    return
示例#4
0
文件: plotters.py 项目: inevity/flent
def init_matplotlib(output, use_markers, load_rc):
    if not HAS_MATPLOTLIB:
        raise RuntimeError("Unable to plot -- matplotlib is missing! Please install it if you want plots.")
    global pyplot, COLOURS
    if output != "-":
        if output.endswith('.svg') or output.endswith('.svgz'):
            matplotlib.use('svg')
        elif output.endswith('.ps') or output.endswith('.eps'):
            matplotlib.use('ps')
        elif output.endswith('.pdf'):
            matplotlib.use('pdf')
        elif output.endswith('.png'):
            matplotlib.use('agg')
        else:
            raise RuntimeError("Unrecognised file format for output '%s'" % output)

    from matplotlib import pyplot

    for ls in LINESTYLES:
        STYLES.append(dict(linestyle=ls))
    for d in DASHES:
        STYLES.append(dict(dashes=d))
    if use_markers:
        for m in MARKERS:
            STYLES.append(dict(marker=m, markevery=10))

    # Try to detect if a custom matplotlibrc is installed, and if so don't
    # load our own values.
    if load_rc \
      and not os.environ['HOME'] in matplotlib.matplotlib_fname() \
      and not 'MATPLOTLIBRC' in os.environ and hasattr(matplotlib, 'rc_file'):
        rcfile = os.path.join(DATA_DIR, 'matplotlibrc.dist')
        if os.path.exists(rcfile):
            matplotlib.rc_file(rcfile)
    COLOURS = matplotlib.rcParams['axes.color_cycle']
def plot_feature_importances_combined(feature_importances, frequency, sorted = False):
    path = os.path.join(plot_folder, str(frequency) + "hz_both_sensors_feature_importances_TFL_data_set_sorted_by_index.png")
    number_of_features = len(feature_importances)
    print(matplotlib.matplotlib_fname())

    indexes = []
    feature_importances_removed_indexes = []
    for i in range(0, number_of_features):
        indexes.append(feature_importances[i][0])
        feature_importances_removed_indexes.append(feature_importances[i][1])
    x = [i for i in range(1, number_of_features+1)]
    print(x)
    print(indexes)
    print(feature_importances_removed_indexes)
    plt.plot(indexes, feature_importances_removed_indexes, 'ro')
    plt.axis([1, 138, 0, feature_importances[0][1]+0.005])
    plt.xticks(x)
    plt.xticks(rotation=90, fontsize=7)
    plt.ylabel("Feature importance", fontsize=17)
    plt.xlabel("\nFeatures (most important at index 1)", fontsize=17)
    plt.title('Averaged feature importance', fontsize = 25)
    fig = matplotlib.pyplot.gcf()
    fig.set_size_inches(25, 8)
    plt.savefig(path)
    plt.show()
    plt.clf()
示例#6
0
 def plot_maintain():
     """"
     maintain or fix for plot
     """
     print(matplotlib_fname())
     print(get_cachedir())
     print([f.name for f in fontManager.ttflist])
示例#7
0
def back2future():
    """
    Activate matplotlib settings from the default matplotlibrc file.
    """
    print("Activating settings from", mpl.matplotlib_fname())
    mpl.rc_file_defaults()
    mpl.rcParams["axes.titlesize"] = "medium"
示例#8
0
def init_matplotlib(output, use_markers, load_rc):
    if not HAS_MATPLOTLIB:
        raise RuntimeError("Unable to plot -- matplotlib is missing! Please install it if you want plots.")
    global pyplot, COLOURS
    if output != "-":
        if output.endswith('.svg') or output.endswith('.svgz'):
            matplotlib.use('svg')
        elif output.endswith('.ps') or output.endswith('.eps'):
            matplotlib.use('ps')
        elif output.endswith('.pdf'):
            matplotlib.use('pdf')
        elif output.endswith('.png'):
            matplotlib.use('agg')
        else:
            raise RuntimeError("Unrecognised file format for output '%s'" % output)

    from matplotlib import pyplot

    for ls in LINESTYLES:
        STYLES.append(dict(linestyle=ls))
    for d in DASHES:
        STYLES.append(dict(dashes=d))
    if use_markers:
        for m in MARKERS:
            STYLES.append(dict(marker=m, markevery=10))

    # Try to detect if a custom matplotlibrc is installed, and if so don't
    # load our own values.
    if load_rc \
      and not os.environ['HOME'] in matplotlib.matplotlib_fname() \
      and not 'MATPLOTLIBRC' in os.environ and hasattr(matplotlib, 'rc_file'):
        rcfile = os.path.join(DATA_DIR, 'matplotlibrc.dist')
        if os.path.exists(rcfile):
            matplotlib.rc_file(rcfile)
    COLOURS = matplotlib.rcParams['axes.color_cycle']
示例#9
0
def show_version(event, context):
    import glob
    import grizli
    import eazy

    print('Event: ', event)

    print('grizli version: ', grizli.__version__)
    print('eazy version: ', eazy.__version__)

    import matplotlib
    print('matplotlibrc: ', matplotlib.matplotlib_fname())
    
    if 'files' in event:
        for file in event['files']:
            print('\n\n === File {0} === \n\n'.format(file))
            with open(file) as fp:
                lines = fp.readlines()
            
            print(''.join(lines))
    
    if 'glob' in event:
        _res = glob.glob(event['glob'])
        print('\n\n === glob {0} === \n\n'.format(event['glob']))
        for file in _res:
            print(file)
示例#10
0
def test_if_rctemplate_is_up_to_date():
    # This tests if the matplotlibrc.template file
    # contains all valid rcParams.
    dep1 = mpl._all_deprecated
    dep2 = mpl._deprecated_set
    deprecated = list(dep1.union(dep2))
    #print(deprecated)
    path_to_rc = mpl.matplotlib_fname()
    with open(path_to_rc, "r") as f:
        rclines = f.readlines()
    missing = {}
    for k,v in mpl.defaultParams.items():
        if k[0] == "_":
            continue
        if k in deprecated:
            continue
        if "verbose" in k:
            continue
        found = False
        for line in rclines:
            if k in line:
                found = True
        if not found:
            missing.update({k:v})
    if missing:
        raise ValueError("The following params are missing " +
                         "in the matplotlibrc.template file: {}"
                         .format(missing.items()))
示例#11
0
def set_style(style='white',
              palette='deep',
              context='poster',
              font='FreeSans',
              font_scale=1.00):
    """Set plot preference in a way that looks good to me.
    """
    import matplotlib.font_manager as font_manager
    import cycler

    # Update font list.
    mpl_data_dir = os.path.dirname(mpl.matplotlib_fname())
    font_files = font_manager.findSystemFonts(
        os.path.join(mpl_data_dir, 'fonts', 'ttf'))
    font_list = font_manager.createFontList(font_files)
    font_manager.fontManager.ttflist.extend(font_list)

    sns.set(
        style=style,
        palette=palette,
        context=context,
        font=font,
        font_scale=font_scale,
    )

    scale_dict = {'paper': 1.3, 'notebook': 1.3, 'talk': 1.4, 'poster': 1.4}
    scale = scale_dict[context]

    plt.rc('axes', linewidth=1.33, labelsize=14)
    plt.rc('xtick', labelsize=10 * scale)
    plt.rc('ytick', labelsize=10 * scale)

    plt.rc('xtick', bottom=True)
    plt.rc('xtick.major', size=5 * scale, width=1.33)
    plt.rc('xtick.minor', size=5 * scale, width=1.33)

    plt.rc('ytick', left=True)
    plt.rc('ytick.major', size=5 * scale, width=1.33)
    plt.rc('ytick.minor', size=5 * scale, width=1.33)

    plt.rc('legend', fontsize=7 * scale)
    plt.rc('grid', color='grey', linewidth=0.5, alpha=0.33)
    plt.rc('font', family=font)

    color_palette = [
        '#005AC8',
        '#AA0A3C',
        '#0AB45A',
        '#FA7850',
        '#8214A0',
        '#FA78FA',
        '#A0FA82',
        '#006E82',
        '#00A0FA',
        '#14D2DC',
        '#F0F032',
        '#FAE6BE',
    ]

    mpl.rcParams['axes.prop_cycle'] = cycler.cycler(color=color_palette)
示例#12
0
def main():
    print("--------------1.第1个figure,全局参数设置------------------------")
    print("rc文件路径: ", plt_lib.matplotlib_fname())  # 查看rc文件路径
    # print(plt_lib.rc_params())  # 查看rc参数
    fig, axes = plt.subplots()

    plt.rcParams['font.family'] = ['SimHei']  # 配置中文显示
    plt.rcParams['axes.unicode_minus'] = False

    x1 = np.arange(0.0, 4.0, 0.5)
    x2 = np.arange(0.0, 4.0, 0.01)
    plt.figure(1)
    plt.subplot(1, 2, 1)  # 第1个子图
    plt.plot(x1, test_fun(x1), 'bo ', x2, test_fun(x2), 'k')
    plt.title('子图1')

    plt.subplot(1, 2, 2)  # 第2个子图
    plt.plot(np.cos(2 * np.pi * x2), 'r--')
    plt.title('sub_2')
    plt.show()

    print("--------------2.第2个figure,rc设置方法------------------------")
    fig = plt.figure()
    # ax = fig.add_subplot(2, 2, 3)
    ax = plt.subplot()
    # ax.plot()可以用plt.plot()代替
    ax.plot(np.random.randn(30).cumsum(), color='r',
            linestyle='dashed', marker='o', label='one')  # 图上的点用圆圈
    ax.plot(np.random.randn(30).cumsum(), color='g',
            linestyle='dashed', marker='+', label='two')  # 点用+
    ax.plot(np.random.randn(30).cumsum(), color='b',
            linestyle='dashed', marker='v', label='three')  # 点用朝下三角形
    ax.legend(loc='best')  # 图列

    plt.show()
示例#13
0
def test_if_rctemplate_would_be_valid(tmpdir):
    # This tests if the matplotlibrc.template file would result in a valid
    # rc file if all lines are uncommented.
    path_to_rc = mpl.matplotlib_fname()
    with open(path_to_rc, "r") as f:
        rclines = f.readlines()
    newlines = []
    for line in rclines:
        if line[0] == "#":
            newline = line[1:]
        else:
            newline = line
        if "$TEMPLATE_BACKEND" in newline:
            newline = "backend : Agg"
        if "datapath" in newline:
            newline = ""
        newlines.append(newline)
    d = tmpdir.mkdir('test1')
    fname = str(d.join('testrcvalid.temp'))
    with open(fname, "w") as f:
        f.writelines(newlines)
    with pytest.warns(None) as record:
        dic = mpl.rc_params_from_file(fname,
                                      fail_on_error=True,
                                      use_default_template=False)
        assert len(record) == 0
示例#14
0
文件: count_ev.py 项目: swonoda/sf
    def analysis_body_summary(self):
        connection = psycopg2.connect(**self.connection_config)
        count_sql = "select body_title, summary_total_count, body_total_count, author from works where body_total_count > 0 and body_total_count < 40000"
        score_count = pd.read_sql(sql=count_sql,
                                  con=connection,
                                  index_col='body_title')
        print(score_count)

        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        sns.set_style('whitegrid')
        sns.set_palette('summer')

        ax = sns.lmplot(x='summary_total_count',
                        y='body_total_count',
                        hue='author',
                        data=score_count,
                        fit_reg=False)
        ax = plt.gca()
        ax.set_title('Summary count vs Total count')
        # ax.set_xlabel('summary_count')
        # ax.set_ylabel('work_count')
        # グラフ表示
        print(mpl.matplotlib_fname())
        plt.show()
示例#15
0
def main():
    """Main entry."""
    args = parse_args()
    if args.cfg_file is not None:
        merge_cfg_from_file(args.cfg_file)
    if args.opts is not None:
        merge_cfg_from_list(args.opts)
    assert os.path.exists(cfg.OUTPUT_PATH)
    setup_logging()
    logger.info('Using matplotlibrc file from %s', mpl.matplotlib_fname())
    # collect results
    if os.path.exists(os.path.join(cfg.OUTPUT_PATH, 'runner.pkl')):
        logger.info('Loading runner from %s',
                    os.path.join(cfg.OUTPUT_PATH, 'runner.pkl'))
        with open(os.path.join(cfg.OUTPUT_PATH, 'runner.pkl'), 'rb') as f:
            runner = pickle.load(f)
    else:
        assert args.def_file is not None and os.path.exists(args.def_file)
        with open(args.def_file, 'r') as f:
            defs = yaml.load(f)
        runner = GenericTestRunner(defs)
        runner.load_results()
    # pack results
    runner.export_data()
    plotter = Plotter(runner, show=(not args.no_show))
    plotter.plot_obj_vs_time()
    plotter.plot_obj_vs_iteration()
    plotter.plot_psnr_vs_time()
示例#16
0
    def run(self):
        """
        Performs the usual install process and then copies the True Type fonts 
        that come with clearplot into matplotlib's True Type font directory, 
        and deletes the matplotlib fontList.cache 
        """
        #Perform the usual install process
        install.run(self)
        #Try to install custom fonts
        try:
            import os, shutil
            import matplotlib
            import matplotlib.font_manager

            #Find where matplotlib stores its True Type fonts
            mpl_data_dir = os.path.dirname(matplotlib.matplotlib_fname())
            mpl_ttf_dir = os.path.join(mpl_data_dir, 'fonts', 'ttf')
            cp_ttf_dir = os.path.dirname(os.path.realpath(__file__))

            file_names = [
                "Times New Roman.ttf", "Arial.ttf", "Courier New.ttf",
                "Courier New Bold.ttf", "Arial Bold.ttf",
                "Times New Roman Bold.ttf"
            ]
            for file in file_names:
                old_path = os.path.join(cp_ttf_dir, "fonts/" + file)
                new_path = os.path.join(mpl_ttf_dir, file)
                shutil.copyfile(old_path, new_path)
            matplotlib.font_manager._rebuild()

        except:
            warnings.warn(
                "WARNING: An issue occured while installing the fonts.")
示例#17
0
def chinese_setting(
    url="http://cnbj1.fds.api.xiaomi.com/browser-algo-nanjing/data/SimHei.ttf"
):
    """
    :param url: SimHei字体下载链接
    :return:
    """
    print('开始设置中文...')
    matplotlibrc_path = Path(matplotlib.matplotlib_fname())
    ttf_path = matplotlibrc_path.parent.__str__() + '/fonts/ttf'
    ttf_url = 'https://raw.githubusercontent.com/Jie-Yuan/Jie-Yuan.github.io/master/SimHei.ttf' if url is None else url
    if list(Path(ttf_path).glob('SimHei.ttf')):
        pass
    else:
        print('下载字体...')
        os.popen("cd %s && wget %s" % (ttf_path, ttf_url)).read()
        os.popen("rm -rf ~/.matplotlib/*.cache").read()

    print('设置字体...')
    setting1 = 'font.family: sans-serif'
    setting2 = 'font.sans-serif: SimHei, Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif'
    setting3 = 'axes.unicode_minus: False'
    os.system('echo > %s' % matplotlibrc_path)
    os.system('echo %s >> %s' % (setting1, matplotlibrc_path))
    os.system('echo %s >> %s' % (setting2, matplotlibrc_path))
    os.system('echo %s >> %s' % (setting3, matplotlibrc_path))

    _rebuild()
    print('请重启kernel测试...')
def ploter(Accountsummny, save=False):
    price = Accountsummny['Close']
    ret = Accountsummny['Account'] / Accountsummny['Close'].shift()
    ret = ret.fillna(0)

    cumret = (1 + ret).cumprod() - 1

    name = matplotlib.matplotlib_fname()
    font = FontProperties(fname=name)
    if len(ret.index.values[0]) >= 12:
        tdate = map(
            lambda x: datetime.strptime(x[:-4], '%Y-%m-%d %H:%M:%S').date(),
            ret.index.values)
    else:
        tdate = map(lambda x: datetime.strptime(x, '%Y%m%d').date(),
                    ret.index.values)

    Fig = plt.figure(figsize=(20, 10))
    pcumret = plt.subplot(3, 1, 1)
    pcumret.plot(
        tdate,
        cumret.values,
        label='Cumret',
        color='b',
    )
    pcumret.legend(loc=2)
    pcumret.set_ylabel('Cumret', fontsize=16)
    pcumret.set_title(u'Blue is Cumret, red is Price', fontsize=16)
    pprice = plt.twinx()

    ###创建公用的y坐标轴
    pprice.plot(tdate, price.values, label='Price', color='r')
    pprice.legend(loc=0)
    pprice.set_ylabel('Price', fontsize=16)

    ### 最大回撤
    pDD = plt.subplot(3, 1, 2)
    pDD.set_ylabel("Drawdown", fontsize=16)
    [_, _, drawdownList] = MaxDD(cumret)
    pDD.fill_between(tdate, drawdownList, color='r')
    pDD.set_title(u'Drawdown', fontsize=16)
    pdown = plt.twinx()
    pdown.plot(
        tdate,
        cumret.values,
        label='Cumret',
        color='b',
    )
    pdown.legend(loc=2)
    pdown.set_ylabel('Cumret', fontsize=16)
    ### 每笔收益
    _, Pnl = stratanalyz(Accountsummny)
    pPnl = plt.subplot(3, 1, 3)
    pPnl.set_ylabel("Pnl", fontsize=16)
    pPnl.bar(range(len(Pnl)), Pnl, color='b')
    pPnl.set_title(u'PnL', fontsize=16)
    plt.show()
    if save == True:
        plt.savefig('Record.png')
示例#19
0
def get_matplotlib_info():
    print('버전: ', mpl.__version__)
    print('설치 위치: ', mpl.__file__)
    print('설정 위치: ', mpl.get_configdir())
    print('캐시 위치: ', mpl.get_cachedir())
    print('설정 파일 위치: ', mpl.matplotlib_fname())
    font_list = fm.findSystemFonts(fontpaths=None, fontext='ttf')
    print(len(font_list))
示例#20
0
    def do_nothing_show(*args, **kwargs):
        frame = inspect.currentframe()
        fname = frame.f_back.f_code.co_filename
        if fname in ('<stdin>', '<ipython console>'):
            warnings.warn("""
Your currently selected backend, '%s' does not support show().
Please select a GUI backend in your matplotlibrc file ('%s')
or with matplotlib.use()""" % (backend, matplotlib.matplotlib_fname()))
示例#21
0
def FindPath():
    """尋找設定檔"""
    import matplotlib 
    strPath=matplotlib.matplotlib_fname()
    """font.family  解除註解"""
    """font.sans-serif : Microsoft JhengHei 新增"""    

    return strPath
示例#22
0
def ShowAndConfigParam():
    mpl.rcParams['font.size'] = 14
    mpl.rcParams['legend.fontsize'] = 'small'
    print "============ configurations ================="
    print "default configuration file: %s" % mpl.matplotlib_fname()
    print "default font size: %s" % mpl.rcParams['font.size']
    print "legend fontsize: %s" % mpl.rcParams['legend.fontsize']
    print "============ configurations ================="
示例#23
0
文件: __init__.py 项目: runt18/nupic
    def do_nothing_show(*args, **kwargs):
        frame = inspect.currentframe()
        fname = frame.f_back.f_code.co_filename
        if fname in ('<stdin>', '<ipython console>'):
            warnings.warn("""
Your currently selected backend, '{0!s}' does not support show().
Please select a GUI backend in your matplotlibrc file ('{1!s}')
or with matplotlib.use()""".format(backend, matplotlib.matplotlib_fname()))
 def build(cls, installation_dir):
     output_path = os.path.join(installation_dir, "matplotlibrc")
     if os.path.exists(output_path) and not options.force:
         raise ValueError(
             f"Output file {output_path} exists. Refusing to overwrite.")
     shutil.copy(matplotlib.matplotlib_fname(), output_path)
     print(
         "\nSee https://matplotlib.org/stable/tutorials/introductory/customizing.html#the-matplotlibrc-file \n"
         "for information on how to edit this file.\n")
示例#25
0
文件: count_ev.py 项目: swonoda/sf
    def clustering(self, cluster_target, n_cluster, title):
        print(title)
        connection = psycopg2.connect(**self.connection_config)
        count_sql = "select body_title, body_score, body_total_count" + "," + cluster_target + \
            ", author from works where body_total_count > 0 and body_total_count < 40000"
        score_count = pd.read_sql(sql=count_sql,
                                  con=connection,
                                  index_col='body_title')
        rate = score_count[cluster_target] / score_count.body_total_count * 100
        print(rate)
        label_rate = cluster_target + "_rate"
        score_count[label_rate] = rate

        model1 = KMeans(n_clusters=n_cluster, random_state=0)
        data = score_count[[label_rate]]
        cluster_mean = model1.fit(data)
        cluster = cluster_mean.labels_
        score_count['cluster'] = cluster
        score_count = score_count.sort_values(label_rate, ascending=True)
        print(score_count)
        score_count.to_csv("data/" + cluster_target + ".csv")

        scatter_table = pd.pivot_table(score_count,
                                       index='author',
                                       columns='cluster',
                                       aggfunc=len,
                                       fill_value=0)
        print(scatter_table[label_rate])
        scatter_table[label_rate].to_csv("data/" + cluster_target +
                                         "_pivot.csv")

        fig = plt.figure()
        ax = fig.add_subplot(1, 1, 1)
        sns.set_style('whitegrid')
        #        sns.set_palette('winter')

        ax = sns.lmplot(x='body_total_count',
                        y='body_score',
                        hue='cluster',
                        data=score_count,
                        fit_reg=False)
        ax = plt.gca()
        ax.set_title(title)
        plt.savefig("data/" + cluster_target + "_score.png", dpi=300)
        plt.clf()
        ax2 = fig.add_subplot(1, 2, 1)
        ax2 = sns.lmplot(x='body_total_count',
                         y=cluster_target,
                         hue='cluster',
                         data=score_count,
                         fit_reg=False)
        plt.savefig("data/" + cluster_target + ".png", dpi=300)
        print(mpl.matplotlib_fname())
        plt.show()
        fig.show()
示例#26
0
def show_version(event, context):
    import grizli
    import eazy
    
    print('Event: ', event)
    
    print('grizli version: ', grizli.__version__)
    print('eazy version: ', eazy.__version__)
    
    import matplotlib
    print('matplotlibrc: ', matplotlib.matplotlib_fname())
示例#27
0
def pre_paper_plot(change=True):
    if not change:
        # Reset back to defaults
        #mpl.rcParams.update(mpl.rcParamsDefault)
        mpl.rcdefaults()
        # Apply own default config (as indicated in the matplotlibrc file)
        params = mpl.rc_params_from_file(mpl.matplotlib_fname())
        mpl.rcParams.update(params)
        return

    plt.rcParams['text.color'] = '000000'
    plt.rcParams['patch.facecolor'] = 'blue'
    plt.rcParams['patch.edgecolor'] = 'black'
    plt.rcParams['axes.facecolor'] = 'white'
    plt.rcParams['axes.edgecolor'] = 'black'
    plt.rcParams['axes.grid'] = False
    plt.rcParams['axes.labelcolor'] = 'black'
    #plt.rcParams['axes.color_cycle'] = '8cd0d3, 7f9f7f, cc9393, 93e0e3, dc8cc3, f0dfaf, dcdccc'
    plt.rcParams['axes.prop_cycle'] = cycler('color', [
        '#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b',
        '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'
    ])
    plt.rcParams['xtick.color'] = 'k'
    plt.rcParams['xtick.direction'] = 'in'
    plt.rcParams['ytick.color'] = 'k'
    plt.rcParams['ytick.direction'] = 'in'
    plt.rcParams['legend.fancybox'] = False
    plt.rcParams['figure.facecolor'] = 'white'
    plt.rcParams['figure.edgecolor'] = 'white'
    plt.rcParams['text.usetex'] = True

    plt.rcParams['figure.figsize'] = (8, 3)
    plt.rcParams['font.size'] = 10
    plt.rcParams['font.family'] = 'Computer Modern'
    plt.rcParams['axes.labelsize'] = 8
    plt.rcParams['axes.titlesize'] = 9
    plt.rcParams['legend.fontsize'] = 9
    plt.rcParams['xtick.labelsize'] = 7
    plt.rcParams['ytick.labelsize'] = 7
    plt.rcParams['savefig.dpi'] = 300
    plt.rcParams['xtick.major.size'] = 3
    plt.rcParams['xtick.minor.size'] = 3
    plt.rcParams['xtick.major.width'] = 1
    plt.rcParams['xtick.minor.width'] = 1
    plt.rcParams['ytick.major.size'] = 3
    plt.rcParams['ytick.minor.size'] = 3
    plt.rcParams['ytick.major.width'] = 1
    plt.rcParams['ytick.minor.width'] = 1
    plt.rcParams['legend.frameon'] = True
    plt.rcParams['legend.edgecolor'] = 'k'
    plt.rcParams['legend.loc'] = 'best'
    plt.rcParams['axes.linewidth'] = 1
    plt.rcParams['legend.handlelength'] = 3
    plt.rcParams['hatch.linewidth'] = 1
def plot_posterior_dose_resp():
    """Plot the posterior dose response.

    Plot the pareto plot, fit to dose response data, and outcome probabilities
    as a function of dose.
    """
    # mpl.rcParams["legend.frameon"] = True
    print(mpl.rcParams["font.family"], mpl.rcParams["font.size"],
          mpl.matplotlib_fname())
    # layout of figure
    lef, rig = 0.10, 0.98
    bot, top = 0.10, 0.95
    hs, ws = 0.48, 0.25
    fig = plt.figure(figsize=(9, 6))
    gs = GridSpec(3,
                  2,
                  top=top,
                  bottom=bot,
                  left=lef,
                  right=rig,
                  hspace=hs,
                  wspace=ws)

    # misc. choices
    col_mo = ["#1b9e77", "#d95f02"]
    part_cols = ["#70a89f", "#fdb462", "#fb8072"]  # colorbrewer 1
    sol_inds = [0, 4]

    ax = plt.subplot(gs[:2, 0])
    pareto_plot(col_mo, sol_inds, ax)
    panel_label("a", ax)

    ax = plt.subplot(gs[:2, 1])
    dr_obj(col_mo, sol_inds, ax)
    panel_label("b", ax)

    ax = plt.subplot(gs[2, :])
    filename = "results/predsbasebase2523823dl" + str(sol_inds[1])
    filename += "r1_1000rep.npz"
    with np.load(filename) as data:
        dose = data["doselist"]
        pinf = data["pinf"]
        pcar = data["pcar"]
        ps = data["ps"]
    partition_plot(dose,
                   pinf[0, ],
                   pcar[0, ],
                   ps[0, ],
                   ax,
                   cols=part_cols,
                   log=True)
    panel_label("c", ax, 0.08)

    plt.savefig("results/figs/posterior_dr.pdf")
示例#29
0
def test0():
    # /Users/a1800101471/.matplotlib
    print('matplotlib的缓存目录:', matplotlib.get_cachedir())
    # /Users/a1800101471/Library/Python/3.7/lib/python/site-packages/matplotlib/mpl-data/matplotlibrc
    print('matplotlib的字体库目录:', matplotlib.matplotlib_fname())
    print('matplotlib的支持字体', plt.rcParams['font.family'])
    print('matplotlib的支持字体', plt.rcParams['font.sans-serif'])
    # plt.rcParams['font.sans-serif'] = ['msyh']

    for f in sorted([f.name for f in matplotlib.font_manager.fontManager.ttflist]):
        print(f)
示例#30
0
def install(robustus, requirement_specifier, rob_file, ignore_index):
    # First install it through the wheeling
    robustus.install_through_wheeling(requirement_specifier, rob_file, ignore_index)
    import matplotlib
    rcfile = matplotlib.matplotlib_fname()
    # Writing the settings to the file --- we may add more is needed
    logging.info('Writing the configuration file %s' % rcfile)
    with open(rcfile, 'w') as f:
        logging.info('Configuring matplotlib to use PySide as the backend...')
        f.write('backend : qt4agg\n')
        f.write('backend.qt4 : PySide\n')
示例#31
0
def show_mplrc_settings():
    """Display information about matplotlibrc file"""
    print 'Using %s' % mpl.matplotlib_fname()
    r = mpl.rcParams

    ff = r['font.family'][0]
    print 'Font sizes for axes: %g; (x,y) ticks: (%g, %g): legend %g' % \
          (r['axes.labelsize'], r['xtick.labelsize'],
           r['ytick.labelsize'], r['legend.fontsize'])
    print 'Font family %s uses face %s' % (ff, r['font.' + ff])

    print 'Figure size: %s, dpi: %g' % (r['figure.figsize'], r['figure.dpi'])
示例#32
0
def show_mplrc_settings():
    """Display information about matplotlibrc file"""
    print 'Using %s' % mpl.matplotlib_fname()
    r = mpl.rcParams

    ff = r['font.family'][0]
    print 'Font sizes for axes: %g; (x,y) ticks: (%g, %g): legend %g' % \
          (r['axes.labelsize'], r['xtick.labelsize'],
           r['ytick.labelsize'], r['legend.fontsize'])
    print 'Font family %s uses face %s' % (ff, r['font.'+ff])

    print 'Figure size: %s, dpi: %g' % (r['figure.figsize'], r['figure.dpi'])
示例#33
0
文件: utils.py 项目: matoken78/python
def adapt_japanese_font(plt):
    dest_font_path = Path(
        mpl.matplotlib_fname()).parent / 'fonts' / 'ttf' / 'ipaexg.ttf'
    source_font_path = Path(__file__).parent / 'font' / 'ipaexg.ttf'
    shutil.copy(str(source_font_path), str(dest_font_path))

    config_dir = Path(mpl.get_configdir())
    for f in config_dir.glob('**/*'):
        if f.is_file():
            f.unlink()
        else:
            f.rmdir()
    plt.rcParams['font.family'] = 'IPAexGothic'
示例#34
0
 def async_wrapper(*args, **kwargs):
     # TODO handle this better in the future, but stop the massive error
     # caused by MacOSX async runs for now.
     try:
         import matplotlib as plt
         if plt.rcParams['backend'] == 'MacOSX':
             raise EnvironmentError(backend_error_template %
                                    plt.matplotlib_fname())
     except ImportError:
         pass
     args = args[1:]
     pool = concurrent.futures.ProcessPoolExecutor(max_workers=1)
     future = pool.submit(self, *args, **kwargs)
     pool.shutdown(wait=False)
     return future
示例#35
0
    def __init__(self, currentFolder,nproc):
        import matplotlib
        matplotlib.use('GTKAgg')
        print 'MATPLOTLIB FILE: %s'%matplotlib.matplotlib_fname()
        
        figureResidualsUI.__init__(self)
        self.currentFolder = currentFolder
        self.nproc = nproc
        [self.timedir,self.fields,curtime] = currentFields(self.currentFolder,nproc=self.nproc)
        self.buttonBox.button(QtGui.QDialogButtonBox.Ok).setEnabled(False)

        for field in self.fields:
            if field not in unknowns:
                continue
            item = QtGui.QListWidgetItem()
            item.setCheckState(QtCore.Qt.Unchecked)
            item.setText(field)
            self.listWidget.addItem(item)
示例#36
0
def _set_matplotlib_default_backend():
    """
    matplotlib will try to print to a display if it is available, but don't want
    to run it in interactive mode. we tried setting the backend to 'Agg'' before
    importing, but it was still resulting in issues. we replace the existing
    backend with 'agg' in the default matplotlibrc. This is a hack until we can
    find a better solution
    """
    if _matplotlib_installed():
        import matplotlib
        matplotlib.use('Agg', force=True)
        config = matplotlib.matplotlib_fname()
        with file_transaction(config) as tx_out_file:
            with open(config) as in_file, open(tx_out_file, "w") as out_file:
                for line in in_file:
                    if line.split(":")[0].strip() == "backend":
                        out_file.write("backend: agg\n")
                    else:
                        out_file.write(line)
示例#37
0
def main():
    x1 = np.linspace(0.0, 5.0)
    x2 = np.linspace(0.0, 2.0)
    
    y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)
    y2 = np.cos(2 * np.pi * x2)
    
    plt.subplot(2, 1, 1)
    plt.plot(x1, y1, 'yo-')
    plt.title('A tale of 2 subplots')
    plt.ylabel('Damped oscillation')
    
    plt.subplot(2, 1, 2)
    plt.plot(x2, y2, 'r.-')
    plt.xlabel('time (s)')
    plt.ylabel('Undamped')
    print(matplotlib.matplotlib_fname())
    #plt.savefig("tmp.png")
    plt.show()
示例#38
0
文件: callable.py 项目: qiime2/qiime2
        def async_wrapper(*args, **kwargs):
            # TODO handle this better in the future, but stop the massive error
            # caused by MacOSX async runs for now.
            try:
                import matplotlib as plt
                if plt.rcParams['backend'] == 'MacOSX':
                    raise EnvironmentError(backend_error_template %
                                           plt.matplotlib_fname())
            except ImportError:
                pass

            # This function's signature is rewritten below using
            # `decorator.decorator`. When the signature is rewritten, args[0]
            # is the function whose signature was used to rewrite this
            # function's signature.
            args = args[1:]

            pool = concurrent.futures.ProcessPoolExecutor(max_workers=1)
            future = pool.submit(self, *args, **kwargs)
            pool.shutdown(wait=False)
            return future
示例#39
0
        def async_wrapper(*args, **kwargs):
            # TODO handle this better in the future, but stop the massive error
            # caused by MacOSX asynchronous runs for now.
            try:
                import matplotlib as plt
                if plt.rcParams['backend'].lower() == 'macosx':
                    raise EnvironmentError(backend_error_template %
                                           plt.matplotlib_fname())
            except ImportError:
                pass

            # This function's signature is rewritten below using
            # `decorator.decorator`. When the signature is rewritten, args[0]
            # is the function whose signature was used to rewrite this
            # function's signature.
            args = args[1:]

            pool = concurrent.futures.ProcessPoolExecutor(max_workers=1)
            future = pool.submit(_subprocess_apply, self, args, kwargs)
            # TODO: pool.shutdown(wait=False) caused the child process to
            # hang unrecoverably. This seems to be a bug in Python 3.7
            # It's probably best to gut concurrent.futures entirely, so we're
            # ignoring the resource leakage for the moment.
            return future
示例#40
0
    These are just different ways of doing the same thing;
    pyplot is the python plotting library on matplotlib and so is pylab,
    but pylab also imports numpy automatically.  By default, just use
    pyplot and import numpy because its cleaner to not pollute namespace.

"""


import matplotlib as mpl  # Only need for configuring default settings
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches  # for legend
import numpy as np


### Default Settings for Matplotlib
print mpl.matplotlib_fname()  # Find configuration file 'matplotlibrc'

### Settings for Pyplot
#plt.switch_backend('agg')
#plt.ion() #Turn on interactive
#plt.ioff() # Non-interactive


def simple_plot():
    """ Do a simple plot """

    ### Setup Different Types of Data
    a = np.linspace(0, 50, 10, endpoint=False)  # start, stop, num=50 (# of samples), endpoint (stop at last sample?)
    print a  # [0, 5, 10, 15, 20, 25, 30, 35, 40, ]
    b  = np.arange(0, 20, 2)  # start, stop, step; returns evenly spaced values given the interval/step
    print b  # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
示例#41
0
#
# oe_generate_legend.py
# The OnEarth Legend Generator.
#
#
# Global Imagery Browse Services
# NASA Jet Propulsion Laboratory
# 2015

import sys
import urllib
import xml.dom.minidom
from optparse import OptionParser
import matplotlib as mpl
mpl.use('Agg')
print(mpl.matplotlib_fname())
from matplotlib import pyplot
from matplotlib import rcParams
import matplotlib.pyplot as plt
from StringIO import StringIO
import numpy as np
import math

# for SVG tooltips
try:
    import lxml.etree as ET
except ImportError:
    import xml.etree.ElementTree as ET
    ET.register_namespace("","http://www.w3.org/2000/svg")

toolName = "oe_generate_legend.py"
示例#42
0
class matplotlib.RcParams(*args, **kwargs)  # класс для хранения параметров
	copy()
	find_all(pattern)
	validate                                     # словарь с функциями валидации
matplotlib.rcParams                         # текущие параметры

matplotlib.rc_context(rc=None, fname=None)  # with rc_context(...) строим график

matplotlib.rc(group, **kwargs)              # устанавливает rc параметры
matplotlib.rc_file(fname)                   # устанавливает параметры из файла
matplotlib.rcdefaults()                     # устанавливает параметры по умолчанию
matplotlib.rc_file_defaults()               # устанавливает параметры из rc файла по умолчанию

matplotlib.rc_params(fail_on_error=False)   # возвращает параметры из rc файла по умолчанию
matplotlib.rc_params_from_file(fname, fail_on_error=False, use_default_template=True) # 
matplotlib.matplotlib_fname()               # путь к файлу с конфигами

matplotlib.interactive(b)                   # устанавливает интерактивность
matplotlib.is_interactive()                 # проверяет интерактивность

####################  module style
import matplotlib.style
matplotlib.style.context(style, after_reset=False)
matplotlib.style.reload_library()
matplotlib.style.use(style)
matplotlib.style.library                    # словарь доступных стилей
matplotlib.style.available                  # список доступных стилей


##################### modeule rcsetup
import matplotlib.rcsetup
示例#43
0
from collections import OrderedDict
from pip._vendor.requests.packages.urllib3.packages import ordered_dict

__author__ = 'aoden'
import pandas as pd
from pandas import DataFrame
import matplotlib
import matplotlib.pyplot as plt
matplotlib.matplotlib_fname()
matplotlib.get_backend()
import threading
import numpy as np

df_2008_pollster = pd.read_csv('2008-polls.csv')
df_2012_pollster = pd.read_csv('2012-polls.csv')
df_2008_result = pd.read_csv('2008-results.csv')
df_2012_result = pd.read_csv('2012-results.csv')

df_2008_pollster = DataFrame(df_2008_pollster)
df_2012_pollster = DataFrame(df_2012_pollster)

pollsters_2008 = df_2008_pollster['Pollster'].tolist()
states_2008 = df_2008_pollster['State'].tolist()

# print(df_2008_pollster[(df_2008_pollster.Pollster == 'Rasmussen') & (df_2008_pollster.State == 'AL')])
unique_2008_pollster = pd.unique(df_2008_pollster.Pollster.ravel())
unique_2008_state = pd.unique(df_2008_pollster.State.ravel())
unique_2012_state = pd.unique(df_2012_pollster.State.ravel())
unique_2012_pollster = pd.unique(df_2012_pollster.Pollster.ravel())
# print unique_2008_pollster
###############################################################################

#######################################
### (b) Use dynamic rc settings

# http://matplotlib.org/users/customizing.html

# matplotlib uses matplotlibrc configuration files to customize all kinds of properties,
# which we call rc settings or rc parameters.
# You can control the defaults of almost every property in matplotlib:
# figure size and dpi, line width, color and style, axes, axis and grid properties, text and font properties and so on.
# rc params can be stored in a file, and transferred across different machines for consistency.

# Find the current location of the rc file
import matplotlib as mpl
mpl.matplotlib_fname()


### DYNAMIC rc SETTINGS
# You can also dynamically change the default rc settings in a python script or
# interactively from the python shell.
# All of the rc settings are stored in a dictionary-like variable called matplotlib.rcParams,
# which is global to the matplotlib package.
# rcParams can be modified directly, for example:
import matplotlib as mpl
mpl.rcParams['lines.linewidth'] = 2
mpl.rcParams['lines.color'] = 'r'

# matplotlib also provides a couple of convenience functions for modifying rc settings.
# The matplotlib.rc() command can be used to modify multiple settings in a single group at once, using keyword arguments:
import matplotlib as mpl
示例#45
0
def main():
    logger  = logging.getLogger(__name__)
    logging.captureWarnings(True)
    logging.basicConfig(format=('%(asctime)s - %(name)s - %(levelname)s - ' +  '%(message)s'), level=logging.DEBUG)
    logger.debug(matplotlib.matplotlib_fname())

    args = docopt(__doc__)
    path = args["<datafile>"]
    out  = args["<outputfile>"]

    tablename   = args["--tablename"]
    bins        = int(args["--bins"])
    title       = args["--title"]

    first_night = args["--first"]
    last_night  = args["--last"]

    theta_cut = float(args['--theta2-cut'])
    prediction_threshold = float(args['--threshold'])

    alpha = 0.2

    df = pd.read_hdf(path, key=tablename)
    df.columns = [c.replace(':', '_') for c in df.columns]

    if first_night:
        df = df.query('(NIGHT >= {})'.format(first_night)).copy()
        logger.info('Using only Data begining with night {}'.format(first_night))

    if last_night:
        df = df.query('(NIGHT <= {})'.format(last_night)).copy()
        logger.info('Using only Data until night {}'.format(last_night))


    night_stats = df.NIGHT.describe()
    actual_first_night = night2datetime(int(night_stats['min']))
    actual_last_night = night2datetime(int(night_stats['max']))

    period = 'Period: {:%Y-%m-%d} to {:%Y-%m-%d}'.format(actual_first_night, actual_last_night)
    logger.debug('Using Nights from {}'.format(period))

    theta_keys = ["Theta"] + ['Theta_Off_{}'.format(off_position) for off_position in range(1, 6)]


    df[theta_keys] = df[theta_keys].apply(theta_mm_to_theta_squared_deg, axis=0)


    # best_significance = 0
    # prediction_threshold = 0
    # theta_cut = 0
    # for threshold in np.linspace(0.5, 1, 20):
    #     df_signal = df.query('(prediction_on > {})'.format(threshold))
    #     df_background = df.query('(background_prediction > {})'.format(threshold))
    #
    #
    #     signal_theta = df_signal['signal_theta'].values
    #     background_theta = df_background['background_theta'].values
    #     theta_cuts = np.linspace(0.5, 0.001, 50)
    #     for theta_cut in theta_cuts:
    #         n_off = len(background_theta[background_theta < theta_cut])
    #         n_on =len(signal_theta[signal_theta < theta_cut])
    #         significance = li_ma_significance(n_on, n_off, alpha=alpha)
    #         if significance > best_significance:
    #             theta_cut = theta_cut
    #             best_significance = significance
    #             prediction_threshold = threshold

    best_significance = 0
    best_prediction_threshold = 0
    best_theta_cut = 0

    for threshold in np.linspace(0.5, 1, 20):
        t_on = df['Theta'][df['prediction_on' ] > threshold]
        t_off = pd.Series()
        for off_position in range(1, 6):
            mask = df['prediction_off_{}'.format(off_position)] > threshold
            t_off = t_off.append(df['Theta_Off_{}'.format(off_position)][mask])
            
        for t_cut in np.linspace(0.5, 0.001, 50):
            n_on = len(t_on[t_on < t_cut])
            n_off = len(t_off[t_off < t_cut])
            significance = li_ma_significance(n_on, n_off, alpha=alpha)
            if significance > best_significance:
                best_theta_cut = t_cut
                best_significance = significance
                best_prediction_threshold = threshold

    logger.info('Maximum Significance {}, for Theta Cut at {} and confidence cut at {}'.format(best_significance, best_theta_cut, best_prediction_threshold))


    theta_on = df['Theta'][df['prediction_on' ] > prediction_threshold]
    theta_off = pd.Series()
    for off_position in range(1, 6):
        mask = df['prediction_off_{}'.format(off_position)] > prediction_threshold
        theta_off = theta_off.append(df['Theta_Off_{}'.format(off_position)][mask])

    n_on = len(theta_on[theta_on < theta_cut])
    n_off = len(theta_off[theta_off < theta_cut])
    logger.info('N_on = {}, N_off = {}'.format(n_on, n_off))

    excess_events = n_on - alpha * n_off
    significance = li_ma_significance(n_on, n_off, alpha=alpha)

    logger.info(
        'Chosen cuts for prediction threshold {} has signifcance: {} with  a theta sqare cut of {}.'.format(
            prediction_threshold, significance, theta_cut
    ))

    theta_max = 0.3
    bins = np.linspace(0, theta_max, bins)

    #Define measures for plot and info box
    info_left = 0.0
    info_height = 0.3
    info_width = 1.0
    info_bottom = 1.
    info_top    = info_bottom + info_height
    info_right  = info_left + info_width
    plot_height = 1. - info_height
    plot_width  = theta_max


    fig = plt.figure()
    fig.subplots_adjust(top=plot_height)
    ax = fig.gca()

    #Plot the Theta2 Distributions
    sig_x, sig_y, sig_norm = histpoints(theta_on, bins=bins, xerr='binwidth', label='On', fmt='none', ecolor='b', capsize=0)
    back_x, back_y, back_norm = histpoints(theta_off, bins=bins, xerr='binwidth', label='Off', fmt='none', ecolor='r', capsize=0, scale=alpha, yerr='sqrt')

    #Fill area underneeth background
    ax.fill_between(back_x, back_y[1], 0, facecolor='grey', alpha=0.2, linewidth=0.0)

    #Mark theta cut with a line0.5*(info_left+info_right),
    ax.axvline(x=theta_cut, linewidth=1, color='k', linestyle='dashed')

    # embed()

    # Draw info Box
    p = patches.Rectangle( (info_left, 1.), info_width, info_height, fill=True, transform=ax.transAxes, clip_on=False, facecolor='0.9', edgecolor='black')
    ax.add_patch(p)

    info_text = 'Significance: {:.2f}, Alpha: {:.2f}\n'.format(significance, alpha)
    if period:
        info_text = period + ',\n' + info_text
    info_text += 'Confidence Cut: {:.2f}, Theta Sqare Cut: {:.2f} \n'.format(prediction_threshold, theta_cut)
    info_text += '{:.2f} excess events, {:.2f} background events \n'.format(excess_events, n_off)

    ax.text(0.5*(info_left+info_right), 0.5*(info_top+info_bottom)-0.05, info_text,
            horizontalalignment='center', verticalalignment='center', fontsize=10, transform=ax.transAxes)

    ax.text(0.5*(info_left+info_right), (info_top), title,
                bbox={'facecolor':'white', 'pad':10},
                horizontalalignment='center',
                verticalalignment='center',
                fontsize=14, color='black',
                transform=ax.transAxes)

        # hist_background, edges , _ = plt.hist(df_background.values, bins=edges, alpha=0.6, label='Off region')
    # plt.xlabel("$//Theta^2 in mm^2$")
    plt.xlabel("Theta^2 / mm^2")
    plt.ylabel("Counts")

    plt.legend(fontsize=12)
    # plt.show()
    plt.savefig(out)
示例#46
0
文件: ml.py 项目: acecodes/acebots
import matplotlib.pyplot as plt
import matplotlib

from sklearn import datasets, svm

# Preferably TkAgg
print("Current backend:", matplotlib.get_backend())
print("Matplotlib location:", matplotlib.matplotlib_fname())

# Sample built-in dataset
digits = datasets.load_digits()

print("Dataset size:", len(digits.data))

# Classifier
clf = svm.SVC(gamma=0.001, C=100)

x, y = digits.data[:-10], digits.target[:-10]
clf.fit(x, y)

print('Prediction:', clf.predict(digits.data[-2]))

plt.imshow(digits.images[-2],
           cmap=plt.cm.gray_r,
           interpolation='nearest')

plt.show()
#!/usr/bin/env python3
# -*- coding: utf-8; mode: python; mode: auto-fill; fill-column: 78 -*-
# Time-stamp: <2016-02-11 15:06:51 (kthoden)>

"""Auswertung
lade csv
"""
import csv
import json
import survey_data
import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.image as image

print("config %s" % mpl.matplotlib_fname())
titles = open("titles.txt", mode="a")
# Set color transparency (0: transparent; 1: solid)
ALPHA_VALUE = 0.7
CHART_COLOUR = "#448CC7"
# using colour scheme from last year's poster
COLOURS = ['#663366', '#cc9900', '#99cccc', '#669966', '#669999', '#99cccc']
CSV_PATH = "csv_sources/"
EXTENSION = "png"                         #or pdf
WIDTH=0.75

def turnaround_dict(dictionary, value_list):
    """Turns
    ist = 'bibarchiv': {'Nein': 5, 'Ja': 93}, 'persoenlich': {'Nein': 39, 'Ja': 59}, 'eigenarchiv': {'Nein': 67, 'Ja': 31}, 'online': {'Nein': 2, 'Ja': 96}}
    into
    eigentlich = {'Nein': {'bibarchiv' : 5, 'persoenlich': 39, 'eigenarchiv': 67, 'online': 2}, 'Ja' : {'bibarchiv' : 93, 'persoenlich': 59, 'eigenarchiv': 31, 'online': 96}}
示例#48
0
# Problem importing pylab in Ubuntu 8.1
&gt;&gt;&gt; import matplotlib
&gt;&gt;&gt; matplotlib.matplotlib_fname()
示例#49
0
文件: ahkab.py 项目: B-Rich/ahkab
def main(filename, outfile="stdout", verbose=3):
    """Method to call ahkab from a Python script with a netlist file.

    **Parameters:**

    filename : string
        The netlist filename.

    outfile : string, optional
        The outfiles base name, the suffixes shown below will be added.
        With the exception of the magic value ``stdout`` which causes
        ahkab to print out instead of to disk.

    verbose : int, optional
        the verbosity level, from 0 (silent) to 6 (debug).
        It defaults to 3, the same as running ahkab through its command
        line interface.

    Filename suffixes, for each analysis:

    - Alternate Current (AC): ``.ac``
    - Direct Current (DC): ``.dc``
    - Operating Point (OP): ``.opinfo``
    - Periodic Steady State (PSS): ``.pss``
    - TRANsient (TRAN): ``.tran``
    - Symbolic: ``.symbolic``

    **Returns:**

    res : dict
        A dictionary containing the computed results.
    """
    printing.print_info_line(
        ("This is ahkab %s running with:" % (__version__), 6), verbose)
    printing.print_info_line(
        ("  Python %s" % (sys.version.split('\n')[0],), 6), verbose)
    printing.print_info_line(("  Numpy %s" % (np.__version__), 6), verbose)
    printing.print_info_line(("  Scipy %s" % (sp.__version__), 6), verbose)
    printing.print_info_line(("  Sympy %s" % (sympy.__version__), 6), verbose)
    printing.print_info_line(("  Tabulate %s" % (tabulate.__version__), 6), verbose)
    if plotting_available:
        printing.print_info_line(("  Matplotlib %s" % (matplotlib.__version__),
                                  6), verbose)
        printing.print_info_line(("  -> backend: %s" %
                                 (matplotlib.get_backend()), 6), verbose)
        printing.print_info_line(("  -> matplotlibrc: %s" %
                                 (matplotlib.matplotlib_fname()), 6), verbose)
    else:
        printing.print_info_line(
            ("  Matplotlib not found.", 6), verbose)


    read_netlist_from_stdin = (filename is None or filename == "-")
    (circ, directives, postproc_direct) = netlist_parser.parse_circuit(
        filename, read_netlist_from_stdin)

    printing.print_info_line(("Checking circuit for common mistakes...", 6),
                             verbose, print_nl=False)
    check, reason = utilities.check_circuit(circ)
    if not check:
        printing.print_general_error(reason)
        sys.exit(3)
    printing.print_info_line(("done.", 6), verbose)

    if verbose > 3 or _print:
        print("Parsed circuit:")
        print(circ)
        print("Models:")
        for m in circ.models:
            circ.models[m].print_model()
        print("")

    ic_list = netlist_parser.parse_ics(directives)
    _handle_netlist_ics(circ, an_list=[], ic_list=ic_list)
    results = {}
    for an in netlist_parser.parse_analysis(circ, directives):
        if 'outfile' not in list(an.keys()) or not an['outfile']:
            an.update(
                {'outfile': outfile + ("." + an['type']) * (outfile != 'stdout')})
        if 'verbose' in list(an.keys()) and (an['verbose'] is None or an['verbose'] < verbose) \
           or not 'verbose' in list(an.keys()):
            an.update({'verbose': verbose})
        _handle_netlist_ics(circ, [an], ic_list=[])
        if verbose >= 4:
            printing.print_info_line(("Requested an.:", 4), verbose)
            printing.print_analysis(an)
        results.update(run(circ, [an]))

    postproc_list = netlist_parser.parse_postproc(circ, postproc_direct)
    if len(postproc_list) > 0 and len(results):
        process_postproc(postproc_list, circ.title, results, outfile)

    return results
示例#50
0
文件: test.py 项目: raddy/copper
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.draw()
plt.show()

import matplotlib
print(matplotlib.matplotlib_fname())
示例#51
0
        rownames.append(thisname)
        # print rownames
        for col_num in lineList:
            # print res_num, colCounter
            mymatrix[res_num, colCounter] = float64(thislinearray[col_num])
            # print mymatrix
            colCounter = colCounter + 1
    # DEBUG
    # print res, colnames, res==colnames
    # end DEBUG
    return mymatrix, rownames, colnames


if __name__ == "__main__":
    print "You are using matplotlib version " + matplotlib.__version__
    print "You can make changes to global plotting options in " + matplotlib.matplotlib_fname()

    parser = OptionParser()
    parser.add_option(
        "-i",
        "--interactive",
        action="store_true",
        default=False,
        help="Runs interactive browser of the mutual information matrix",
    )
    parser.add_option("-f", "--filename", default="2esk_demo.txt", help="Filename of mutInf matrix")

    (options, args) = parser.parse_args()

    j = mutInfmat(  #'/home/ahs/r3/Ubc1/wt/Ubc1p_wt/Ubc1p_wt.reslist-nsims6-structs20081-bin30_bootstrap_avg_mutinf_res_sum_0diag.txt',[])
        # options.filename,[])
示例#52
0
	for samps,symbol,colour,label in zip([samps1],["s"],["r"],["My samples"]):
		
		

		for comp in [0.9]:	
				for key,value in samps.iteritems():
					print key
					P_vals=[]
					mf_vals=[]
					for h2o in h2o_vals:
					
						ti_corrected=value.get_ti_corrected(0.9,h2o,0.25)
						mf_vals.append(value.quick_mf(ti_corrected,0.09,0.123))
					#P_vals.append(value.lee_pt_decimal(comp,h2o,[0.25,0.25])[0][1])
#						if ti_corrected==0:
#							print key
					plt.plot(h2o_vals,mf_vals,marker=".",markersize=10)
plt.legend()
plt.xlabel("H$_2$O wt%")
plt.ylabel("Ti melt Fraction")
fig1=plt.gcf()
fig1.set_size_inches(24, 12)
directory="figures/"#+"%s"%(comp.replace("=","_")) #%(sub_zone,comp.replace("=","_"))
if not os.path.exists(directory):
		os.makedirs(directory)
import matplotlib
print matplotlib.matplotlib_fname()
fig1.savefig("%sti_mf_vs_h2o.png"%(directory),bbox_inches='tight',dpi=(149))
plt.show()
# -*- coding:utf-8 -*-

import matplotlib

file_path = matplotlib.matplotlib_fname()
print file_path
#
#with open(file_path) as f:
#    for line in f.readlines():
#        if not line.startswith('# '):
#            print line

print matplotlib.rcParams

print matplotlib.rcParams['lines.linewidth']

matplotlib.rc('lines', linewidth=2, color='r')

matplotlib.rcdefaults()


#!/usr/bin/python3
# coding: utf-8
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
print(matplotlib.matplotlib_fname())  # 将会获得 matplotlib 包所在文件夹
# 然后执行下面的操作
# sudo cp msyh.ttf /usr/share/fonts/
# cp msyh.ttf ~/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data/fonts/ttf
# cd ~/anaconda3/lib/python3.6/site-packages/matplotlib/mpl-data
# vim matplotlibrc  # 删除 font.family 和 font.sans-serif 两行前的 #, 并在 font.sans-serif 后添加中文字体 Microsoft YaHei, ...(其余不变)
# rm -rf ~/.cache/matplotlib/*
##################################################################
## 打印出可用的字体
## 系统可用中文字体
import subprocess
output = subprocess.check_output('fc-list :lang=zh -f "%{family}\n"', shell=True)
print( '*' * 10, '系统可用的中文字体', '*' * 10)
print(output)  # 编码有问题
zh_fonts = set(f.split(',', 1)[0] for f in output.decode('utf-8').split('\n'))
print(zh_fonts)

## matplotlib 可用所有字体
from matplotlib import font_manager
mat_fonts = set(f.name for f in font_manager.FontManager().ttflist)
available = mat_fonts & zh_fonts
print ('*' * 10, '可用的字体', '*' * 10)
for f in available: print (f)

## 另一种方法获得 matplotlib 可用所有字体
import pandas as pd
示例#55
0
import numpy as np
import csv
#from Animation import AnimatedScatter
import pandas
import multiprocessing
from matplotlib_panel import MatplotlibPanel
from OneD_Plot_Methods import one_d_line_plot, OneD_Line_Same_XAxis, OneD_Compare_Plots
from TwoD_Plot_Methods import TwoD_Scatter, TwoD_Hexbin
from ThreeD_Plot_Methods import ThreeD_Scatter
import XMLParser
from Helpers import DataSize, ChangeBaseAxis, ComparePlots
import wx.lib.agw.flatnotebook as fnb
from wx.lib.colourdb import getColourList
import subprocess
import matplotlib
file_matplotlibrc = matplotlib.matplotlib_fname()


"""
Uncomment this line if you want to replace your matplotlib settings file with the one, available in this repository
subprocess.call["cp", matplotlibrc, file_matplotlibrc]
"""

#This list has all the colors available in wx python
colors = [color for color in getColourList()]



class RedirectText(object):
	def __init__(self, aWxTextCtrl):
		self.out = aWxTextCtrl
示例#56
0
文件: mpl.py 项目: goerz/mgplottools
def new_figure(fig_width, fig_height, size_in_cm=True, style=None, no_backend=False, quiet=False, **kwargs):
    """
    Return a new matplotlib figure of the specified size (in cm by default)

    Information about the matplotlib backend, settings and the figure will be
    printed on STDOUT, unless `quiet=True` is given.

    The remaining kwargs are passed to the Figure init routine

    Arguments
    ---------

    fig_width: float
        total width of figure canvas, in cm (or inches if `size_in_cm=False`

    fig_height: float
        total height of figure canvas, in cm (or inches if `size_in_cm=False`

    size_in_cm: boolean, optional
        give as False to indicate that `fig_width` and `fig_height` are in
        inches instead of cm

    style: string or array of strings, optional
        A style file to overwrite or ammend the matplotlibrc file. For
        matplotlib version >=1.4, the style sheet feature will be used, see
        <http://matplotlib.org/users/style_sheets.html>
        In older versions of matplotlib, `style` must a filename or URL string;
        the contents of the file will be merged with the matplotlibrc settings

    no_backend: boolean, optional
        If given as True, skip the use of the pyplot entirely, creating the
        figure in a purely object-oriented way.

    quiet: boolean, optional

    Notes
    -----

    You may use the figure as follows, assuming the pyplot is used
    (`no_backend=False`)

    >>> import matplotlib
    >>> matplotlib.use('PDF') # backend ('PDF' for pdf, 'Agg' for png)
    >>> fig = mgplottools.mpl.new_figure(10, 4)
    >>> pos = [0.05, 0.05, 0.9, 0.9] # left, bottom offset, width, height
    >>> ax = fig.add_axes(pos)
    >>> ax.plot(linspace(0, 10, 100), linspace(0, 10, 100))
    >>> fig.savefig('out.pdf', format='pdf')

    Alternatively, for a GUI backend, instead of `fig.savefig()`, you can
    display all created figures using `fig.show()` -- it is set up as an alias
    to matplotlib.pyplot.show().

    If you want to do any interactive plotting in ipython (i.e. manipulating
    the plot after its creation), make sure to load the %matplotlib or %pylab
    magic functions. Also, you must use pyplot

    >>> import matplotlib.pyplot as plt

    Do not use `plt.ion()`, which does not work in ipython.
    Simply create a figure, then call `plt.show()` and `plt.draw()`

    If not using a backend (`no_backend=True`, bypassing the pyplot state
    machine), you must create the canvas manually. Consider using the
    `show_fig`, `write_pdf`, `write_eps`, and `write_png` routines
    """
    if no_backend:
        from matplotlib.figure import Figure as figure

        backend = "N/A"
        using_pyplot = False
    else:
        using_pyplot = True
        from matplotlib.pyplot import figure

        backend = matplotlib.get_backend().lower()

    if not quiet:
        print("Using backend: %s" % backend)
        print("Using maplotlibrc: %s" % matplotlib.matplotlib_fname())
    if style is not None:
        try:
            import matplotlib.style as mpl_style

            mpl_style.use(style)
            if not quiet:
                print("Using style: %s" % style)
        except ImportError:
            if not quiet:
                print(
                    "The style package was added to matplotlib in version "
                    "1.4. It is not available in your release.\n"
                )
                print("Using fall-back implementation")
            try:
                from matplotlib import rc_params_from_file

                rc = rc_params_from_file(style, use_default_template=False)
                matplotlib.rcParams.update(rc)
            except:
                print("Style '%s' not found" % style)
        except ValueError as e:
            print("Error loading style %s: %s" % (style, e))

    if size_in_cm:
        if not quiet:
            print("Figure height: %s cm" % fig_height)
            print("Figure width : %s cm" % fig_width)
        fig = figure(figsize=(fig_width * cm2inch, fig_height * cm2inch), **kwargs)
    else:
        if not quiet:
            print("Figure height: %s cm" % (fig_height / cm2inch))
            print("Figure width : %s cm" % (fig_width / cm2inch))
        fig = figure(figsize=(fig_width, fig_height), **kwargs)
    if using_pyplot:
        # replace fig.show() with matplotlib.pyplot.show()
        from matplotlib.pyplot import show

        fig.show = show
    return fig

# add filemode="w" to overwrite
# add a date or time stamp
logging.basicConfig(filename="sample.log", filemode="w", level=logging.INFO)

logging.debug("This is a debug message")
logging.info("Informational message")
logging.error("An error has happened!")


import inspect

import matplotlib as mpl
print('matplotlib: ', mpl.__version__)
print('matplotlib.matplotlib_fname(): ',mpl.matplotlib_fname())

# Force matplotlib to not use any Xwindows backend
# useful when you want to turn off plt.show()
try: mpl.use('Agg')
except: pass

# Fonts, latex:
mpl.rc('font',**{'family':'serif', 'serif':['TimesNewRoman']})
mpl.rc('text', usetex=True)
#mpl.rcParams['text.usetex']=True


import matplotlib.pyplot as plt
import numpy as np
print('numpy: ', np.__version__)