Example #1
0
    def test_get_group_colors(self):
        """get_group_colors should iterate over color groups correctly."""

        data_colors = color_dict_to_objects(self.data_color_hsv)
        exp = (self.colors, data_colors, self.data_color_order)
        obs = get_group_colors(self.groups, self.colors, data_colors, self.data_color_order)

        self.assertEqual(obs, exp)
Example #2
0
    def test_get_group_colors(self):
        """get_group_colors should iterate over color groups correctly."""

        data_colors = color_dict_to_objects(self.data_color_hsv)
        exp = (self.colors, data_colors, self.data_color_order)
        obs=get_group_colors(self.groups,self.colors,data_colors,\
                             self.data_color_order)

        self.assertEqual(obs, exp)
Example #3
0
def make_all_charts(data,dir_path,filename,num_categories,colorby,args,\
                        color_data, prefs,background_color,label_color,
                        chart_type,generate_image_type,plot_width,plot_height,\
                        bar_width,dpi,resize_nth_label,label_type,\
                        include_html_legend,include_html_counts):
    """Generate interactive charts in one HTML file"""

    #iterate over the preferences and assign colors according to taxonomy
    img_data = []
    for label,f_name in data:
        raw_fpath=os.path.join(dir_path,'raw_data',os.path.split(f_name)[-1])
        # move raw file to output directory
        shutil.copyfile(f_name,raw_fpath)
        
        f = color_data['counts'][f_name]
        level = max([len(t.split(';')) - 1 for t in f[1]])
        
        for key in prefs.keys():
            if prefs[key]['column'] != str(level):
                continue
            col_name = 'Taxon'
            mapping = [['Taxon']]
            mapping.extend([[m] for m in f[1]])
            if 'colors' in prefs[key]:
                if isinstance(prefs[key]['colors'], dict):
                    pref_colors = prefs[key]['colors'].copy() 
                    #copy so we can mutate
                else:
                    pref_colors = prefs[key]['colors'][:]
            else:
                pref_colors={}
            labelname=prefs[key]['column']

            #Define groups and associate appropriate colors to each group
            groups = group_by_field(mapping, col_name)
            pref_colors, data_colors, data_color_order = \
                get_group_colors(groups, pref_colors)
        
        updated_pref_colors={}
        
        if chart_type=='area' and len(f[0])==1:
            raise ValueError, 'When generating area charts, the number of samples (or category values) must be greater than 1.  However, you can still produce a pie chart or bar chart with only 1 sample (or category value), but you must remove the area chart value from the input arguments.'
        
        for key in pref_colors:
            updated_pref_colors[key.replace('"','')]=pref_colors[key]
        
        for i,val in enumerate(f[1]):
            f[1][i]=val.replace('"','')
            
        #parse the counts and continue processing
        img_data.extend(get_counts(label.strip(),colorby,num_categories,\
                        dir_path,level,f,prefs,updated_pref_colors,\
                        background_color,\
                        label_color,chart_type,generate_image_type,\
                        plot_width,plot_height,bar_width,dpi,raw_fpath,\
                        resize_nth_label,label_type,include_html_legend,\
                        include_html_counts))

    #generate html filepath
    outpath = os.path.join(dir_path,'%s_charts.html' % chart_type)
    out_table = ''.join(img_data)
    #write out html file
    write_html_file(out_table,outpath)
Example #4
0
def make_pie_chart(data,
                   dir_path,
                   level,
                   color_data,
                   prefs,
                   background_color,
                   label_color,
                   file_prefix=None,
                   props={},
                   y_len=6.5,
                   dpi=80,
                   generate_eps=False,
                   generate_pdf=True,
                   others_key="All Other Categories",
                   others_color="#eeeeee",
                   should_capitalize=True):
    """
    Write interactive piechart 

    data: [fraction:label,...] 

    trunc_len: truncates labels after this many chars

    """
    if not data:
        raise ValueError, "No data available for pie chart."

    all_fracs = []
    all_labels = []
    colors = []
    for key in prefs.keys():
        if prefs[key]['column'] != str(level):
            continue
        col_name = 'Taxon'
        mapping = [['Taxon']]
        mapping.extend([[m] for m in color_data[1]])
        if 'colors' in prefs[key]:
            if isinstance(prefs[key]['colors'], dict):
                pref_colors = prefs[key]['colors'].copy(
                )  #copy so we can mutate
            else:
                pref_colors = prefs[key]['colors'][:]
        else:
            pref_colors = {}
        labelname = prefs[key]['column']

        #Define groups and associate appropriate colors to each group
        groups = group_by_field(mapping, col_name)
        pref_colors, data_colors, data_color_order = \
            get_group_colors(groups, pref_colors)

    # set up labels and colors for pie chart
    for color_ix, (c_label, c_frac) in enumerate(data):
        #commented out the following line, since the key becomes invalid when
        #replacing part of the string.
        #c_label = c_label.replace("_", " ")
        # we also want to color others category same every time
        if c_label == others_key:
            colors.append(others_color)
        else:
            colors.append(data_colors[pref_colors[c_label]].toHex())
        all_fracs.append(c_frac)
        if should_capitalize:
            capital = "%s (%.2f%%)" % (c_label.capitalize(), (c_frac * 100.0))
            all_labels.append(capital)
        else:
            all_labels.append("%s (%.2f%%)" % (c_label, (c_frac * 100.0)))
    rc('font', size='10')
    rc('text', color=label_color)
    rc('patch', linewidth=.1)
    rc('axes', linewidth=.5, edgecolor=label_color)
    rc('text', usetex=False)
    fig = figure(randrange(10000), figsize=(2 * y_len, y_len))

    fp = FontProperties()
    fp.set_size('8')
    if len(data) > 30:
        loc = 4
    else:
        loc = 5
    mtitle = "Pie Chart"
    if "title" in props:
        mtitle = props["title"]
    axis('off')
    title(mtitle, fontsize='10', color=label_color)
    ax = axes([0.0, 0.0, .5, 1])
    p1 = pie(all_fracs, shadow=False, colors=colors)
    flg = figlegend(p1[0],labels = all_labels, loc = loc, borderpad=0.3, \
                 labelspacing=0.3, prop = fp)
    flg.legendPatch.set_alpha(0.0)
    #write out
    if file_prefix is None:
        img_name = make_img_name()
    else:
        img_name = file_prefix
    img_abs = os.path.join(dir_path, 'pie_charts', img_name)
    savefig(img_abs, dpi=dpi, facecolor=background_color)
    eps_link = ""
    eps_abs = ""

    if generate_pdf:
        if file_prefix is None:
            eps_img_name = make_img_name(file_ext=".pdf")
        else:
            eps_img_name = file_prefix + ".pdf"
        savefig(os.path.join(dir_path, 'pie_charts', eps_img_name),
                facecolor=background_color)
        eps_abs = os.path.join('pie_charts', eps_img_name)
        eps_link = DOWNLOAD_LINK % ((os.path.join('pie_charts',\
                eps_img_name)),\
        IMG_SRC % (os.path.join('pie_charts',img_name)))
    if generate_eps:
        if file_prefix is None:
            eps_img_name = make_img_name(file_ext=".eps")
        else:
            eps_img_name = file_prefix + ".eps"
        savefig(os.path.join(dir_path, 'pie_charts', eps_img_name),
                facecolor=background_color)
        strip_eps_font(os.path.join(dir_path, 'pie_charts', eps_img_name))
        out = getoutput("gzip " +
                        os.path.join(dir_path, 'pie_charts', eps_img_name))
        eps_abs = os.path.join(dir_path, 'pie_charts', eps_img_name) + ".gz"
        eps_link=DOWNLOAD_LINK % ((os.path.join('pie_charts', eps_img_name)+".gz"),\
        IMG_SRC % (os.path.join('pie_charts',img_name)))
    close(fig)
    clf()
    return eps_link, IMG_SRC_2 % (os.path.join('pie_charts', img_name))