예제 #1
0
 def _get_font_afm(self, prop):
     key = hash(prop)
     font = self.afmfontd.get(key)
     if font is None:
         fname = findfont(prop, fontext='afm')
         font = self.afmfontd.get(fname)
         if font is None:
             font = AFM(file(findfont(prop, fontext='afm')))
             self.afmfontd[fname] = font
         self.afmfontd[key] = font
     return font
예제 #2
0
파일: testing.py 프로젝트: junlysky/obspy
    def __enter__(self):
        """
        Set matplotlib defaults.
        """
        MatplotlibBackend.switch_backend("AGG", sloppy=False)

        from matplotlib import font_manager, rcParams, rcdefaults
        import locale

        try:
            locale.setlocale(locale.LC_ALL, native_str('en_US.UTF-8'))
        except Exception:
            try:
                locale.setlocale(locale.LC_ALL,
                                 native_str('English_United States.1252'))
            except Exception:
                msg = "Could not set locale to English/United States. " + \
                      "Some date-related tests may fail"
                warnings.warn(msg)

        # set matplotlib builtin default settings for testing
        rcdefaults()
        if self.style is not None:
            self.style.__enter__()
        if MATPLOTLIB_VERSION >= [2, 0, 0]:
            default_font = 'DejaVu Sans'
        else:
            default_font = 'Bitstream Vera Sans'
        rcParams['font.family'] = default_font
        with warnings.catch_warnings(record=True) as w:
            warnings.filterwarnings('always', 'findfont:.*')
            font_manager.findfont(default_font)
            if w:
                warnings.warn('Unable to find the ' + default_font + ' font. '
                              'Plotting tests will likely fail.')
        try:
            rcParams['text.hinting'] = False
        except KeyError:
            warnings.warn("could not set rcParams['text.hinting']")
        try:
            rcParams['text.hinting_factor'] = 8
        except KeyError:
            warnings.warn("could not set rcParams['text.hinting_factor']")

        if self.plt_close_all_enter:
            import matplotlib.pyplot as plt
            try:
                plt.close("all")
            except Exception:
                pass
        return self
예제 #3
0
 def _get_font_afm(self, prop):
     key = hash(prop)
     font = self.afmfontd.get(key)
     if font is None:
         fname = findfont(prop, fontext='afm', directory=self._afm_font_dir)
         if fname is None:
             fname = findfont(
                 "Helvetica", fontext='afm', directory=self._afm_font_dir)
         font = self.afmfontd.get(fname)
         if font is None:
             font = AFM(file(fname))
             self.afmfontd[fname] = font
         self.afmfontd[key] = font
     return font
def test_font_priority():
    with rc_context(rc={
            'font.sans-serif':
            ['cmmi10', 'Bitstream Vera Sans']}):
        font = findfont(
            FontProperties(family=["sans-serif"]))
    assert_equal(os.path.basename(font), 'cmmi10.ttf')
예제 #5
0
def test_find_ttc():
    fp = FontProperties(family=["WenQuanYi Zen Hei"])
    if Path(findfont(fp)).name != "wqy-zenhei.ttc":
        # Travis appears to fail to pick up the ttc file sometimes.  Try to
        # rebuild the cache and try again.
        fm._rebuild()
        assert Path(findfont(fp)).name == "wqy-zenhei.ttc"

    fig, ax = plt.subplots()
    ax.text(.5, .5, "\N{KANGXI RADICAL DRAGON}", fontproperties=fp)
    fig.savefig(BytesIO(), format="raw")
    fig.savefig(BytesIO(), format="svg")
    with pytest.raises(RuntimeError):
        fig.savefig(BytesIO(), format="pdf")
    with pytest.raises(RuntimeError):
        fig.savefig(BytesIO(), format="ps")
예제 #6
0
 def _get_font(self, prop):
     fname = findfont(prop)
     font = get_font(fname)
     font.clear()
     size = prop.get_size_in_points()
     font.set_size(size, 72.0)
     return font
예제 #7
0
def test_fontinfo():
    import matplotlib.font_manager as font_manager
    import matplotlib.ft2font as ft2font
    fontpath = font_manager.findfont("Bitstream Vera Sans")
    font = ft2font.FT2Font(fontpath)
    table = font.get_sfnt_table("head")
    assert table['version'] == (1, 0)
예제 #8
0
    def _get_agg_font(self, prop):
        """
        Get the font for text instance t, cacheing for efficiency
        """
        if __debug__: verbose.report('RendererAgg._get_agg_font',
                                     'debug-annoying')

        key = hash(prop)
        font = RendererAgg._fontd.get(key)

        if font is None:
            fname = findfont(prop)
            font = RendererAgg._fontd.get(fname)
            if font is None:
                font = FT2Font(
                    fname,
                    hinting_factor=rcParams['text.hinting_factor'])
                RendererAgg._fontd[fname] = font
            RendererAgg._fontd[key] = font

        font.clear()
        size = prop.get_size_in_points()
        font.set_size(size, self.dpi)

        return font
예제 #9
0
def test_font_priority():
    with rc_context(rc={"font.sans-serif": ["cmmi10", "Bitstream Vera Sans"]}):
        # force the font manager to rebuild it self
        _rebuild()
        font = findfont(FontProperties(family=["sans-serif"]))
    assert_equal(os.path.basename(font), "cmmi10.ttf")
    # force it again
    _rebuild()
예제 #10
0
 def _get_font(self, prop):
     """
     Find the `FT2Font` matching font properties *prop*, with its size set.
     """
     fname = font_manager.findfont(prop)
     font = get_font(fname)
     font.set_size(self.FONT_SCALE, self.DPI)
     return font
예제 #11
0
def test_afm_kerning():
    from matplotlib.afm import AFM
    from matplotlib.font_manager import findfont

    fn = findfont("Helvetica", fontext="afm")
    with open(fn, 'rb') as fh:
        afm = AFM(fh)
    assert afm.string_width_height('VAVAVAVAVAVA') == (7174.0, 718)
예제 #12
0
 def _get_font(self, prop):
     """
     find a ttf font.
     """
     fname = font_manager.findfont(prop)
     font = FT2Font(str(fname))
     font.set_size(self.FONT_SCALE, self.DPI)
     return font
예제 #13
0
def draw_font_table(path):
    """
    Draw a font table of the first 255 chars of the given font.

    Parameters
    ----------
    path : str or None
        The path to the font file.  If None, use Matplotlib's default font.
    """
    if path is None:
        path = fm.findfont(fm.FontProperties())  # The default font.

    font = FT2Font(path)
    # A charmap is a mapping of "character codes" (in the sense of a character
    # encoding, e.g. latin-1) to glyph indices (i.e. the internal storage table
    # of the font face).
    # In FreeType>=2.1, a Unicode charmap (i.e. mapping Unicode codepoints)
    # is selected by default.  Moreover, recent versions of FreeType will
    # automatically synthesize such a charmap if the font does not include one
    # (this behavior depends on the font format; for example it is present
    # since FreeType 2.0 for Type 1 fonts but only since FreeType 2.8 for
    # TrueType (actually, SFNT) fonts).
    # The code below (specifically, the ``chr(char_code)`` call) assumes that
    # we have indeed selected a Unicode charmap.
    codes = font.get_charmap().items()

    labelc = ["{:X}".format(i) for i in range(16)]
    labelr = ["{:02X}".format(16 * i) for i in range(16)]
    chars = [["" for c in range(16)] for r in range(16)]

    for char_code, glyph_index in codes:
        if char_code >= 256:
            continue
        row, col = divmod(char_code, 16)
        chars[row][col] = chr(char_code)

    fig, ax = plt.subplots(figsize=(8, 4))
    ax.set_title(path)
    ax.set_axis_off()

    table = ax.table(
        cellText=chars,
        rowLabels=labelr,
        colLabels=labelc,
        rowColours=["palegreen"] * 16,
        colColours=["palegreen"] * 16,
        cellColours=[[".95" for c in range(16)] for r in range(16)],
        cellLoc='center',
        loc='upper left',
    )
    for key, cell in table.get_celld().items():
        row, col = key
        if row > 0 and col > -1:  # Beware of table's idiosyncratic indexing...
            cell.set_text_props(fontproperties=fm.FontProperties(fname=path))

    fig.tight_layout()
    plt.show()
예제 #14
0
파일: testing.py 프로젝트: 3rdcycle/obspy
    def __enter__(self):
        """
        Set matplotlib defaults.
        """
        from matplotlib import font_manager, get_backend, rcParams, rcdefaults
        import locale

        try:
            locale.setlocale(locale.LC_ALL, native_str('en_US.UTF-8'))
        except:
            try:
                locale.setlocale(locale.LC_ALL,
                                 native_str('English_United States.1252'))
            except:
                msg = "Could not set locale to English/United States. " + \
                      "Some date-related tests may fail"
                warnings.warn(msg)

        if get_backend().upper() != 'AGG':
            import matplotlib
            try:
                matplotlib.use('AGG', warn=False)
            except TypeError:
                msg = "Image comparison requires matplotlib backend 'AGG'"
                warnings.warn(msg)

        # set matplotlib builtin default settings for testing
        rcdefaults()
        rcParams['font.family'] = 'Bitstream Vera Sans'
        with warnings.catch_warnings(record=True) as w:
            warnings.filterwarnings('always', 'findfont:.*')
            font_manager.findfont('Bitstream Vera Sans')
        if w:
            warnings.warn('Unable to find the Bitstream Vera Sans font. '
                          'Plotting tests will likely fail.')
        try:
            rcParams['text.hinting'] = False
        except KeyError:
            warnings.warn("could not set rcParams['text.hinting']")
        try:
            rcParams['text.hinting_factor'] = 8
        except KeyError:
            warnings.warn("could not set rcParams['text.hinting_factor']")
        return self
예제 #15
0
def test_font_priority():
    with rc_context(rc={"font.sans-serif": ["cmmi10", "Bitstream Vera Sans"]}):
        font = findfont(FontProperties(family=["sans-serif"]))
    assert_equal(os.path.basename(font), "cmmi10.ttf")

    # Smoketest get_charmap, which isn't used internally anymore
    font = get_font(font)
    cmap = font.get_charmap()
    assert len(cmap) == 131
    assert cmap[8729] == 30
예제 #16
0
def graph(data, username):
    # In order for this to work on Windows, the matplotlib module has to be reimported
    # every time; otherwise the script will crash eventually. (Don't ask me why)
    import matplotlib.pyplot as plt
    from matplotlib import font_manager

    font_manager.findfont("Times New Roman")

    plt.clf()
    N = 24
    ind = np.arange(N)
    width = 1

    p1 = plt.bar(ind, data, width, color="#ccccff", linewidth=1.0)
    plt.xlim(0, 24)
    plt.ylim(0.00000001, plt.ylim()[1])
    chars = max([len(("%f" % t).rstrip("0").rstrip(".")) for t in plt.yticks()[0]])
    if chars > 4:
        adjustment = 0.019 * (chars - 4)
    else:
        adjustment = 0.0

    fig = plt.figure(figsize=(8, 6))
    ax = fig.add_subplot(1, 1, 1)
    ax.yaxis.grid(color="black", linestyle="solid", linewidth=1.5)
    ax.xaxis.grid(color="black", linestyle="solid", linewidth=1.5)

    p1 = plt.bar(ind, data, width, color="#ccccff", linewidth=1.0)
    plt.xlim(0, 24)
    plt.ylim(0.00000001, plt.ylim()[1])
    plt.gcf().subplots_adjust(left=0.125 + adjustment)

    plt.xlabel("Time (UTC)")
    plt.ylabel("Posts / hour")
    plt.title("u/" + username.replace("_", "$\_$"))
    plt.xticks(np.arange(25), ("12am", "", "6am", "", "12pm", "", "6pm", "", "12am"))
    plt.xticks(np.arange(0, 25, 3))
    plt.rcParams.update({"font.size": 22, "font.style": "bold"})
    plt.rc("font", family="serif")
    plt.rc("font", serif="Times New Roman")
    plt.gcf().subplots_adjust(bottom=0.12)
    plt.savefig("graph.png")
예제 #17
0
 def _get_font(self, prop):
     key = hash(prop)
     font = self.fontd.get(key)
     if font is None:
         fname = findfont(prop)
         font = FT2Font(str(fname))
         self.fontd[key] = font
     font.clear()
     size = prop.get_size_in_points()
     font.set_size(size, 72.0)
     return font
예제 #18
0
    def _get_agg_font(self, prop):
        """
        Get the font for text instance t, cacheing for efficiency
        """
        fname = findfont(prop)
        font = get_font(fname)

        font.clear()
        size = prop.get_size_in_points()
        font.set_size(size, self.dpi)

        return font
예제 #19
0
def test_font_priority():
    with rc_context(rc={
            'font.sans-serif':
            ['cmmi10', 'Bitstream Vera Sans']}):
        font = findfont(FontProperties(family=["sans-serif"]))
    assert Path(font).name == 'cmmi10.ttf'

    # Smoketest get_charmap, which isn't used internally anymore
    font = get_font(font)
    cmap = font.get_charmap()
    assert len(cmap) == 131
    assert cmap[8729] == 30
예제 #20
0
파일: test_rcmod.py 프로젝트: 13052/seaborn
def has_verdana():
    """Helper to verify if Verdana font is present"""
    # This import is relatively lengthy, so to prevent its import for
    # testing other tests in this module not requiring this knowledge,
    # import font_manager here
    import matplotlib.font_manager as mplfm
    try:
        verdana_font = mplfm.findfont('Verdana', fallback_to_default=False)
    except:
        # if https://github.com/matplotlib/matplotlib/pull/3435
        # gets accepted
        return False
    # otherwise check if not matching the logic for a 'default' one
    try:
        unlikely_font = mplfm.findfont("very_unlikely_to_exist1234",
                                       fallback_to_default=False)
    except:
        # if matched verdana but not unlikely, Verdana must exist
        return True
    # otherwise -- if they match, must be the same default
    return verdana_font != unlikely_font
예제 #21
0
	def findFont(self, props):
		from matplotlib.font_manager import FontProperties, findfont

		# search for the best match
		font = FontProperties( fname=findfont( FontProperties(**props) ) )

		props = {
			'family' : font.get_name(),
			'weight' : font.get_weight(),
			'style' : font.get_style(),
		}
		return props
예제 #22
0
파일: visualize.py 프로젝트: JoM-Lab/JoM
def plot_trend(kws, cnts, norm_factors, xlbs, metadata):
    '''Trend of a set of keywords.

    :param List[str] kws: keywords
    :param cnts: counts of keywords
    :type cnts: List[List[int]]
    :param norm_factors: total number of tweets in each time period
    :type norm_factors: List[Int]
    :param List[str] xlbs: labels in x-axis
    :param metadata: authors and time range in str
    :type metadata: List[Object]
    '''
    fig, ax = plt.subplots()

    xs = np.arange(len(xlbs))
    plt.xticks(xs, xlbs)
    plt.xlim(xs[0]-0.1, xs[-1]+0.1)

    xlabels = ax.get_xticklabels()
    # limit the number of x-axis labels
    show_indices = set(range(len(xlabels))[::len(xlabels)//14+1])
    show_indices |= set([len(xlabels)-1])
    for i in range(len(xlabels)):
        if i not in show_indices:
            xlabels[i]._visible = False
        xlabels[i].set_rotation(45)

    # generate colors for each line
    colors = [plt.cm.jet(i) for i in np.linspace(0.1, 0.9, len(kws))]
    for kw, cnt, color in zip(kws, cnts, colors):
        cnt_normalized = [c / nf if nf != 0 else 0
                          for c, nf in zip(cnt, norm_factors)]
        # make it smooth
        xs_new = np.linspace(min(xs), max(xs), 100)
        smooth_func = interp1d(xs, cnt_normalized, kind=min(len(xs)-1, 3))
        # round the decimal to 5
        cnt_smooth = np.around(smooth_func(xs_new), 5)
        # no negagive values
        cnt_smooth[cnt_smooth < 0] = 0
        # limit the word length in legend box
        kw = '{}...'.format(kw[:7]) if len(kw) > 10 else kw
        ax.plot(xs_new, cnt_smooth, '-', label=kw, color=color)

    # place the figure on the left
    box = ax.get_position()
    ax.set_position([box.x0 - 0.03, box.y0 + 0.15,
                     box.width * 0.8, box.height * 0.8])
    # place the legend on the right
    ax.legend(bbox_to_anchor=(1.05, 1.), loc=2, borderaxespad=0.,
              prop=fm.FontProperties(fname=fm.findfont('Source Han Sans CN')))
    plt.title('{} ngram in {}/{}'.format(', '.join(metadata[0]), *(metadata[1])))
    fig.savefig("trend.png")
예제 #23
0
    def _get_agg_font(self, prop):
        """
        Get the font for text instance t, cacheing for efficiency
        """
        if __debug__:
            verbose.report("RendererAgg._get_agg_font", "debug-annoying")

        fname = findfont(prop)
        font = get_font(fname, hinting_factor=rcParams["text.hinting_factor"])

        font.clear()
        size = prop.get_size_in_points()
        font.set_size(size, self.dpi)

        return font
예제 #24
0
 def _get_font(self, prop):
     key = hash(prop)
     font = self.fontd.get(key)
     if font is None:
         fname = findfont(prop)
         font = self.fontd.get(fname)
         if font is None:
             #print "Using font",str(fname)
             #print type(prop)
             font = FT2Font(str(fname))
             self.fontd[fname] = font
         self.fontd[key] = font
     font.clear()
     font.set_size(prop.get_size_in_points(), self.dpi)
     return font
예제 #25
0
 def _get_font_ttf(self, prop):
     """
     get the true type font properties, used because EMFs on
     windows will use true type fonts.
     """
     key = hash(prop)
     font = _fontd.get(key)
     if font is None:
         fname = findfont(prop)
         if debugText: print "_get_font_ttf: name=%s" % fname
         font = FT2Font(str(fname))
         _fontd[key] = font
     font.clear()
     size = prop.get_size_in_points()
     font.set_size(size, self.dpi)
     return font
예제 #26
0
def test_hinting_factor(factor):
    font = findfont(FontProperties(family=["sans-serif"]))

    font1 = get_font(font, hinting_factor=1)
    font1.clear()
    font1.set_size(12, 100)
    font1.set_text('abc')
    expected = font1.get_width_height()

    hinted_font = get_font(font, hinting_factor=factor)
    hinted_font.clear()
    hinted_font.set_size(12, 100)
    hinted_font.set_text('abc')
    # Check that hinting only changes text layout by a small (10%) amount.
    np.testing.assert_allclose(hinted_font.get_width_height(), expected,
                               rtol=0.1)
예제 #27
0
파일: visualize.py 프로젝트: JoM-Lab/JoM
def gen_word_cloud(freqs):
    '''Word cloud!

    :param freqs: word and frequency
    :type freqs: List[(str, cnt)]
    '''
    # bash to the background image
    base_img = os.path.join(os.path.dirname(__file__), "uomi.png")
    # path to otf file
    font_path = fm.findfont('Source Han Sans CN')\
                  .replace('Regular', 'ExtraLight')
    wc = WordCloud(background_color="white", mask=imread(base_img),
                   font_path=font_path,
                   max_words=150, max_font_size=30, scale=2  # random_state=42
                   ).generate_from_frequencies(freqs)
    wc.to_file("wordcloud.png")
예제 #28
0
def get_fontspec():
    """Build fontspec preamble from rc."""
    latex_fontspec = []
    texcommand = rcParams["pgf.texsystem"]

    if texcommand != "pdflatex":
        latex_fontspec.append("\\usepackage{fontspec}")

    if texcommand != "pdflatex" and rcParams["pgf.rcfonts"]:
        families = ["serif", "sans\\-serif", "monospace"]
        commands = ["setmainfont", "setsansfont", "setmonofont"]
        for family, command in zip(families, commands):
            # 1) Forward slashes also work on Windows, so don't mess with
            # backslashes.  2) The dirname needs to include a separator.
            path = pathlib.Path(fm.findfont(family))
            latex_fontspec.append(r"\%s{%s}[Path=%s]" % (
                command, path.name, path.parent.as_posix() + "/"))

    return "\n".join(latex_fontspec)
예제 #29
0
 def _get_agg_font(self, prop):
     """
     Get the font for text instance t, cacheing for efficiency
     """
     if __debug__:
         verbose.report("RendererAgg._get_agg_font", "debug-annoying")
     key = hash(prop)
     font = self._fontd.get(key)
     if font is None:
         fname = findfont(prop)
         font = self._fontd.get(fname)
         if font is None:
             font = FT2Font(str(fname))
             self._fontd[fname] = font
         self._fontd[key] = font
     font.clear()
     size = prop.get_size_in_points()
     font.set_size(size, self.dpi)
     return font
예제 #30
0
def print_glyphs(path):
    """
    Print the all glyphs in the given font file to stdout.

    Parameters
    ----------
    path : str or None
        The path to the font file.  If None, use Matplotlib's default font.
    """
    if path is None:
        path = fm.findfont(fm.FontProperties())  # The default font.

    font = FT2Font(path)

    charmap = font.get_charmap()
    max_indices_len = len(str(max(charmap.values())))

    print("The font face contains the following glyphs:")
    for char_code, glyph_index in charmap.items():
        char = chr(char_code)
        name = unicodedata.name(
                char,
                f"{char_code:#x} ({font.get_glyph_name(glyph_index)})")
        print(f"{glyph_index:>{max_indices_len}} {char} {name}")
예제 #31
0
 def bad_idea(n):
     b.wait()
     for j in range(100):
         font = fm.get_font(fm.findfont("DejaVu Sans"))
         font.set_text(str(n), 0.0, flags=LOAD_NO_HINTING)
예제 #32
0
plt.rcParams["font.family"] = ['Microsoft JhengHei']
plt.rcParams["font.sans-serif"] = ['SimSei']  # SimSei:此黑體必須在無襯線底下才會有
# plt.rcParams["font.sans-serif"] = ['Arial']
# !!查找現有的字型名稱
# =====================================================================
# 【字體設定方式2:rc】可詳細設定,一次設定,多次使用,會影響全域性字型
# font = {"family":"Microsoft JhengHei","weight":"bold","size":"14"}
# plt.rc('font',**font)
# plt.rc('axes',unicode_minus=False)
# =====================================================================
# 【字體設定方式3:fontProperties】
# plt.xlabel("2020日期",fontProperties="SimSun") # 不會影響其它字型設定
# 用時才設定,不會汙染全域性字型設定,靈活
# !!查找字型路徑
from matplotlib.font_manager import findfont, FontProperties
findfont(FontProperties(family=FontProperties().get_family()))
# C:\ProgramData\Anaconda3\Lib\site-packages\matplotlib\mpl-data\fonts\ttf
print(plt.rcParams["font.sans-serif"], "目前使用字型")

print("=== 臺灣銀行黃金牌位分析 " + '=' * 30)
df = pd.read_html('https://rate.bot.com.tw/gold/chart/year/TWD')  #pandas讀取html
df1 = df[0][["日期", "本行買入價格"]]  #只取需要的列表元素
df2 = df[0][["日期", "本行賣出價格"]]  #取第二筆賣出資料
df1.index = pd.to_datetime(df1["日期"], format="%Y/%m/%d")  #將日期格式化並設為index索引
df1.sort_index(inplace=True)  #將索引(日期)反排序
df2.index = pd.to_datetime(df2["日期"], format="%Y/%m/%d")  #將日期格式化並設為index索引
df2.sort_index(inplace=True)  #將索引(日期)反排序

# pandas的to_datetime 可格式化日期,轉成可運算的格式
# print(df.index[0],'<< 格式化')
# print(type(df.index[0]),'<< 類型')
예제 #33
0
#matplotlib.style.use('ggplot')
matplotlib.use( "Agg" )
import matplotlib.pyplot as plt
#import matplotlib as matplotlib
#matplotlib.use( "Agg" )
import matplotlib.patches as patches
import matplotlib.pyplot as plt
import matplotlib.patheffects as path_effects
import numpy as np
from matplotlib import font_manager
import warnings

with warnings.catch_warnings():
    warnings.simplefilter("error")
    try:
        font_file = font_manager.findfont(font_manager.FontProperties(family='Arial'))
        matplotlib.rcParams["font.family"] = "Arial"
    except UserWarning:
        pass
from . import hallagram 
from . import plot, config
from plot import scatter_matrix

def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument( "association_number",
                         help="Association number to be plotted",
                         type=int )
    parser.add_argument( "--input",
                         help="HAllA output directory",
                         default='./' )
예제 #34
0
 def find_matplotlib_font(**kw):
     prop = FontProperties(**kw)
     path = findfont(prop, directory=matplotlib.get_data_path())
     return FontProperties(fname=path)
예제 #35
0
def fitdistrib(picklefile, scales=None):
    from matplotlib.font_manager import findfont, FontProperties
    from matplotlib.ticker import FormatStrFormatter
    majorFormatter = FormatStrFormatter('%.2f')

    fs = 20  # FontProperties.get_size(FontProperties())
    if 'Time' not in findfont(FontProperties()):
        fs = 20
    print "FONT: %s, %d" % (findfont(FontProperties()), fs)
    fs = fs - 2
    params = {
        'axes.labelsize': fs,
        'xtick.labelsize': fs - 3,
        'ytick.labelsize': fs - 3,
        'legend.fontsize': fs - 2,
        'legend.handletextpad': 0.2
    }
    pl.rcParams.update(params)

    if NOPICKLE:
        print "you must install pickle to read in the distributions and fit them"
        return -1
    assert (os.path.isfile(picklefile)), "missing pickled file %s" % picklefile
    pklfile = open(picklefile, 'rb')
    res = pickle.load(pklfile)
    print scales
    if scales:
        testingdiags = scales.split(',')
    else:
        testingdiags = ['E(B-V)', 'D02', 'M13_N2', 'KD02comb']

    print "\n\n###testing with scales: ", testingdiags,
    print "###\n\n"
    ebvs = res['E(B-V)'].T
    nm = len(ebvs)
    Ndata = len(ebvs[0])
    assert (Ndata > 0), "something is wrong with your distribution"
    invalids = [
        sum(np.isnan(res[testingdiags[1]].T[i])) +
        sum(np.isnan(res[testingdiags[2]].T[i])) +
        sum(np.isnan(res[testingdiags[3]].T[i])) for i in range(nm)
    ]
    myi, = np.where(invalids == min(invalids))
    try:
        myi = myi[1]  # in case there are more than one solutions
    except IndexError:
        try:
            myi = myi[0]
        except IndexError:
            pass
    xold = np.zeros(10)
    assert(Ndata - invalids[myi] > 0),\
    "something is wrong with your distribution. " +\
    "Perhaps one of the default scale has all invalid values? " +\
    "try select different scales"
    # -- plotting utils
    fwid = 10.  # fig width
    rat = 1.  # fig aspect ratio
    offx = 0.08  # x offset in figure coords
    offy = 0.05  # y offset in figure coords
    psz = 0.4  # size of the plot in figure width coords
    nr = 2  # number of row plots
    nc = 2  # number of col plots

    fig, axx = pl.subplots(nr, nc, figsize=(fwid, fwid / rat))
    print fig

    for i, d in enumerate(testingdiags):
        ii, jj = int(i / 2), int((i + 1) / 2) - int(i / 2)
        ax = axx[ii][jj]
        ax.set_position([
            jj / float(nc) + offx, 1.0 - (ii + 1) / float(nr) + offy, psz,
            psz * rat
        ])
        for f in [0.1, 0.25, 0.5, 0.75, 1]:
            n0 = int(f * Ndata)
            x = np.random.choice(res[d].T[myi], n0, replace=False)
            #print res[d].T[myi]
            x = x[x > 0]

            x.sort()
            #print x
            n = len(x)

            Px_cuml = np.linspace(0, 1, n)
            # set up an interpolation of the inverse cumulative distribution
            #tck = interpolate.splrep(Px_cuml, x)

            # sample evenly along the cumulative distribution, and interpolate
            #Px_cuml_sample = np.linspace(0, 1, 10 * n)

            #x_sample = interpolate.splev(Px_cuml_sample, tck)

            indices = np.linspace(0, n - 1, 20).astype(int)
            ax.set_ylim(0, 1.05)
            ax.plot(x[indices], Px_cuml[indices], 'o', lw=0, label="%d" % n0)
            ax.plot(x, Px_cuml, '-k')
            maxleft, maxright = min(x), max(x)
            D, p = stats.ks_2samp(x, xold)
            print "KS test for %s n = %d D = %.2g; p = %.2g" % (d, n0, D, p)
            xold = x.copy()
            lims = ax.set_xlim((maxleft, maxright))
        axratio = (lims[1] - lims[0]) / 1.05
        ax.set_aspect(aspect=axratio)

        ax.set_title('%s Cumulative Distribution' % d.replace('_', ' '),
                     fontsize=fs)
        ax.set_xlabel('$x$')
        ax.set_ylabel('$p(<x)$')
        ax.xaxis.set_major_formatter(majorFormatter)

        ax.legend(scatterpoints=1, loc=4)
        xticks = ax.get_xticks()
        dx = xticks[-1] - xticks[-2]
        xticks = xticks[(xticks < maxright) * (xticks > maxleft)]
        while (maxright - xticks[-1]) < 0.25 * dx:
            xticks = xticks[:-1]
    pl.xticks(xticks, ['%.2f' % s for s in xticks])
    pl.savefig(picklefile.replace('.pkl', '_testcomplete.pdf'))
    pl.show()
예제 #36
0
def plot_result(result_dict, show_windows=True, savefile=None):
    import os
    from matplotlib import rcParams
    from matplotlib.font_manager import findfont, FontProperties

    rcParams['font.family'] = 'sans-serif'
    rcParams['font.sans-serif'] = [
        u'Microsoft Yahei',
        u'Heiti SC',
        u'Heiti TC',
        u'STHeiti',
        u'WenQuanYi Zen Hei',
        u'WenQuanYi Micro Hei',
        u"文泉驿微米黑",
        u'SimHei',
    ] + rcParams['font.sans-serif']
    rcParams['axes.unicode_minus'] = False

    use_chinese_fonts = True
    font = findfont(FontProperties(family=['sans-serif']))
    if "/matplotlib/" in font:
        use_chinese_fonts = False
        system_log.warn("Missing Chinese fonts. Fallback to English.")

    import numpy as np
    import matplotlib
    from matplotlib import gridspec
    import matplotlib.image as mpimg
    import matplotlib.pyplot as plt

    summary = result_dict["summary"]
    title = summary['strategy_file']

    total_portfolios = result_dict["total_portfolios"]
    benchmark_portfolios = result_dict.get("benchmark_portfolios")

    index = total_portfolios.index

    # maxdrawdown
    xs = total_portfolios.portfolio_value.values
    rt = total_portfolios.total_returns.values
    max_dd_end = np.argmax(np.maximum.accumulate(xs) / xs)
    if max_dd_end == 0:
        max_dd_end = len(xs) - 1
    max_dd_start = np.argmax(xs[:max_dd_end])

    # maxdrawdown duration
    al_cum = np.maximum.accumulate(xs)
    a = np.unique(al_cum, return_counts=True)
    start_idx = np.argmax(a[1])
    m = a[0][start_idx]
    al_cum_array = np.where(al_cum == m)
    max_ddd_start_day = al_cum_array[0][0]
    max_ddd_end_day = al_cum_array[0][-1]

    max_dd_info = "MaxDD  {}~{}, {} days".format(index[max_dd_start], index[max_dd_end],
                                                 (index[max_dd_end] - index[max_dd_start]).days)
    max_dd_info += "\nMaxDDD {}~{}, {} days".format(index[max_ddd_start_day], index[max_ddd_end_day],
                                                    (index[max_ddd_end_day] - index[max_ddd_start_day]).days)

    plt.style.use('ggplot')

    red = "#aa4643"
    blue = "#4572a7"
    black = "#000000"

    plots_area_size = 0
    if "plots" in result_dict:
        plots_area_size = 5

    figsize = (18, 6 + int(plots_area_size * 0.9))
    plt.figure(title, figsize=figsize)
    max_height = 10 + plots_area_size
    gs = gridspec.GridSpec(max_height, 8)

    # draw logo
    ax = plt.subplot(gs[:3, -1:])
    ax.axis("off")
    filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), "resource")
    filename = os.path.join(filename, "ricequant-logo.png")
    img = mpimg.imread(filename)
    ax.imshow(img, interpolation="nearest")
    ax.autoscale_view()

    # draw risk and portfolio

    font_size = 12
    value_font_size = 11
    label_height, value_height = 0.8, 0.6
    label_height2, value_height2 = 0.35, 0.15

    def _(txt):
        return gettext(txt) if use_chinese_fonts else txt

    fig_data = [
        (0.00, label_height, value_height, _("Total Returns"), "{0:.3%}".format(summary["total_returns"]), red, black),
        (0.15, label_height, value_height, _("Annual Returns"), "{0:.3%}".format(summary["annualized_returns"]), red, black),
        (0.00, label_height2, value_height2, _("Benchmark Returns"), "{0:.3%}".format(summary.get("benchmark_total_returns", 0)), blue,
         black),
        (0.15, label_height2, value_height2, _("Benchmark Annual"), "{0:.3%}".format(summary.get("benchmark_annualized_returns", 0)),
         blue, black),

        (0.30, label_height, value_height, _("Alpha"), "{0:.4}".format(summary["alpha"]), black, black),
        (0.40, label_height, value_height, _("Beta"), "{0:.4}".format(summary["beta"]), black, black),
        (0.55, label_height, value_height, _("Sharpe"), "{0:.4}".format(summary["sharpe"]), black, black),
        (0.70, label_height, value_height, _("Sortino"), "{0:.4}".format(summary["sortino"]), black, black),
        (0.85, label_height, value_height, _("Information Ratio"), "{0:.4}".format(summary["information_ratio"]), black, black),

        (0.30, label_height2, value_height2, _("Volatility"), "{0:.4}".format(summary["volatility"]), black, black),
        (0.40, label_height2, value_height2, _("MaxDrawdown"), "{0:.3%}".format(summary["max_drawdown"]), black, black),
        (0.55, label_height2, value_height2, _("Tracking Error"), "{0:.4}".format(summary["tracking_error"]), black, black),
        (0.70, label_height2, value_height2, _("Downside Risk"), "{0:.4}".format(summary["downside_risk"]), black, black),
    ]

    ax = plt.subplot(gs[:3, :-1])
    ax.axis("off")
    for x, y1, y2, label, value, label_color, value_color in fig_data:
        ax.text(x, y1, label, color=label_color, fontsize=font_size)
        ax.text(x, y2, value, color=value_color, fontsize=value_font_size)
    for x, y1, y2, label, value, label_color, value_color in [
        (0.85, label_height2, value_height2, _("MaxDD/MaxDDD"), max_dd_info, black, black)]:
        ax.text(x, y1, label, color=label_color, fontsize=font_size)
        ax.text(x, y2, value, color=value_color, fontsize=8)

    # strategy vs benchmark
    ax = plt.subplot(gs[4:10, :])

    ax.get_xaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator())
    ax.get_yaxis().set_minor_locator(matplotlib.ticker.AutoMinorLocator())
    ax.grid(b=True, which='minor', linewidth=.2)
    ax.grid(b=True, which='major', linewidth=1)

    # plot two lines
    ax.plot(total_portfolios["total_returns"], label=_("strategy"), alpha=1, linewidth=2, color=red)
    if benchmark_portfolios is not None:
        ax.plot(benchmark_portfolios["total_returns"], label=_("benchmark"), alpha=1, linewidth=2, color=blue)

    # plot MaxDD/MaxDDD
    ax.plot([index[max_dd_end], index[max_dd_start]], [rt[max_dd_end], rt[max_dd_start]],
            'v', color='Green', markersize=8, alpha=.7, label=_("MaxDrawdown"))
    ax.plot([index[max_ddd_start_day], index[max_ddd_end_day]],
            [rt[max_ddd_start_day], rt[max_ddd_end_day]], 'D', color='Blue', markersize=8, alpha=.7, label=_("MaxDDD"))

    # place legend
    leg = plt.legend(loc="best")
    leg.get_frame().set_alpha(0.5)

    # manipulate axis
    vals = ax.get_yticks()
    ax.set_yticklabels(['{:3.2f}%'.format(x * 100) for x in vals])

    # plot user plots
    if "plots" in result_dict:
        plots_df = result_dict["plots"]

        ax2 = plt.subplot(gs[11:, :])
        for column in plots_df.columns:
            ax2.plot(plots_df[column], label=column)

        leg = plt.legend(loc="best")
        leg.get_frame().set_alpha(0.5)

    if show_windows:
        plt.show()

    if savefile:
        fnmame = savefile
        if os.path.isdir(savefile):
            fnmame = os.path.join(savefile, "{}.png".format(summary["strategy_name"]))
        plt.savefig(fnmame, bbox_inches='tight')
예제 #37
0
 def _thread(fonts):
     for f in fonts:
         font_manager.findfont(f)