コード例 #1
0
def plot_cnt_graph(
        xvs,  # x values
        cnt1y,  # y values,
        cnt2y,
        title=None,
        label=None,
        save_name=None,
        y_label=None,
        x_label=None):
    plt.figure(figsize=(15, 6))
    p1 = plt.bar(xvs, cnt1y, 0.35, label="1")
    p2 = plt.bar(xvs, cnt2y, 0.35, bottom=cnt1y, label="2")

    if title:
        plt.title(title)  # 'io-static {} performance'.format(label))
    if y_label:
        plt.ylabel(y_label)
    if x_label:
        plt.xlabel(x_label)

    plt.set_xscale('log')
    plt.set_xticks(xvs)
    plt.set_xticklabels([i / 1024 for i in xvs], rotation=0)

    plt.grid('on', axis='x')
    plt.grid('on', axis='y')

    plt.legend()

    if save_name:
        plt.savefig(save_name)

    return ax
コード例 #2
0
def draw_one(plt, data, training):
    width = 0.35
    with_numbers = [0] * training.num_actions
    without_numbers = [0] * training.num_actions
    labels = list(range(training.num_actions))
    for k in data:
        with_numbers[k], without_numbers[k] = data[k]

    plt.bar([i - (width/2) for i in labels], with_numbers, width, label="with")
    plt.bar([i + (width/2) for i in labels], without_numbers, width, label="without")
    plt.set_xticks(labels)
    plt.set_xticklabels(labels)
    plt.legend()
コード例 #3
0
def plot_cnot_prob(cnot):
    probs = cnot[0]
    x = [1, 2, 3, 4]
    rects = plt.bar(x, probs)
    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x() + rect.get_width() / 2.,
                 1.05 * height,
                 f'{height:.3f}',
                 ha='center',
                 va='bottom')
    plt.set_xticklabels(['|00>', '|01>', '|10>', '|11>'])
    plt.set_ylim(0., 1.4)
    plt.show()
コード例 #4
0
def generate_grouped_plots(
    df: pd.DataFrame,
    k: int,
    utterance_subset: str,
    normalize: bool = True,
    cluster_labels: Dict = {},
    cluster_subset: List = [],
    group_subset: List = [],
    savedir: str = "",
    fn: str = "proportions.pdf",
):
    """
    @param df dataframe of results
    @param k number of clusters
    @param cluster_labels dict mapping int cluster nums to labels
    @param utterance_subset question, answer
    @param savedir dir to save output
    """

    grouped = group_by_cluster_and_speaker(
        df=df,
        k=k,
        utterance_subset=utterance_subset,
        # cluster_labels=cluster_labels,
    )
    # do not use cluster_labels because we need to use the cluster nums
    # in subset_df below

    if normalize:
        speaker_pct = grouped[grouped.columns].div(grouped.totals, axis=0)
        speaker_pct.drop(["totals"], axis=1, inplace=True)
        speaker_pct = subset_df(speaker_pct, cluster_subset, group_subset)
        speaker_pct.rename(cluster_labels, axis="columns", inplace=True)
        plt = speaker_pct.plot.bar(stacked=False)
    else:
        grouped.drop(["totals"], axis=1, inplace=True)
        grouped = subset_df(grouped, cluster_subset, group_subset)
        grouped.rename(cluster_labels, axis="columns", inplace=True)
        plt = grouped.plot.bar(stacked=False)

    formatted_xlabels = [
        "\n".join(wrap(i, 20)) for i in grouped.index.tolist()
    ]

    plt.legend(bbox_to_anchor=(1.05, 1))
    plt.set_xticklabels(formatted_xlabels)
    plt.set_ylabel(f"Percent of {utterance_subset.title()}")

    plt.figure.savefig(os.path.join(savedir, fn))
コード例 #5
0
def barch(plt):
	years = [ "1996", "2001", "2007", "2012" ]
	krange = tuple(range(1,6+1))
	def ind(yr):
		return years.index (yr)

	hm = {}
	hm[1] = [0] * 2 + [1] * 3 + [2] * 6 + [3] * 13
	hm[2] = [0] * 2 + [1] * 4 + [2] * 2 + [3] * 6
	hm[3] = [0] * 6 + [1] * 10+ [2] * 11+ [3] * 14
	hm[4] = [0] * 19+ [1] * 27+ [2] * 18+ [3] * 32
	hm[5] = [0] * 36+ [1] * 27+ [2] * 11+ [3] * 12
	hm[6] = [0] * 0 + [1] * 0 + [2] * 0 + [3] * 0
	m = [hm[v] for v in krange]
	total = { 0 : 2+2+6+19+36+0, 1 : 3+4+10+27+27+0, 2 : 6+2+11+18+11+0, 3 : 13+6+14+32+12+0 }

	colors = ["#88ccee", "#44aa99", "#999933", "#DDCC77", "#CC6677", "#882255", "#AA4499" ]
	#colors = ["#222222", "#666666", "#aaaaaa", "#eeeeee", "#dddddd", "#882255", "#AA4499" ]
	colors = colors[0:len(krange)]


	plt.set(xlabel='Survey year')
	plt.set(ylabel ='MOI (across samples)')
	plt.set_xticks(range(4))
	plt.set_xticklabels (years)
	plt.set (xlim=[-0.5,3.5])
	plt.yaxis.set_major_formatter(mtick.PercentFormatter())
	plt.set (ylim = [0,100])

	weights = np.array ([[100.0 / float(total[int(y)]) for y in hm[v]] for v in krange])
	bins = np.arange (len(years)+1) - 0.5
	hatch='/'
	_, _, patches = plt.hist(m, bins=bins, histtype='bar', stacked=True, weights=weights, rwidth=0.5, color=colors, label=["%d%s strain%s" % (v, "" if v != krange[-1] else "+", "s" if v != krange[0] else "") for v in krange]) #, hatch=hatch)
	plt.legend (bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0, prop={'size':10}, )

	mm = np.array(m)
	lk = { year : { v : len(list (filter (lambda y:y==ind(year), hm[v]))) for v in krange } for year in years }
	for j,bc in enumerate(patches):
		for i,p in enumerate(bc):
			l = lk[years[i]][krange[j]]
			if l == 0:
				continue
			h1 = p.get_height()
			print ("{} {}".format(p,l))
			z = 100.0 * l / float(sum(lk[years[i]].values()))
			plt.text (p.get_x() + p.get_width() / 2., p.get_y() + h1 / 2., "%d%%" % int(z), ha="center", va="center", color="black", fontsize=8, fontweight="normal")
コード例 #6
0
def getGraph(pos, neg):
    N = 1
    positive = pos
    negative = neg
    ind = np.arange(N)  # the x locations for the groups
    width = 0.02  # the width of the bars: can also be len(x) sequence

    fig, plt = plt.subplots()
    rects1 = plt.bar(ind, positive, width, color='#4bf3a2')

    rects2 = plt.bar(ind + width, negative, width, color='#f25454')

    # add some text for labels, title and axes ticks
    plt.set_xticklabels(ind)
    plt.set_yticks((np.arange(0, 1.1, 0.10)))
    plt.legend((rects1[0], rects2[0]), ('Postive', 'Negative'))

    canvas = fig.canvas
    return canvas
コード例 #7
0
for k, v in data.items():
    print(f'{k}\t{len(v)}')

df = pandas.DataFrame(data)

# Sort the dataframe by reverse order
df = df.sort_values(by=plotcols, ascending=[False for x in plotcols])

print(df.head())

# Now plot that linegraph!
#fig = plt.figure(figsize=(6,8))
#ax = fig.add_subplot(111)

#for i, v in enumerate(plotcols):
#ax.plot('name', v, data=df, marker='', color=colors[i], linewidth=2)
df.plot(kind='bar', stacked=True, colors=colors, figsize=(6, 8))

# calculate how many contigs to plot on x xaxis
cval = int(len(data["name"]) / 25)

#ax.set_xticklabels([str(x) if x % cval == 0 else "" for x in range(len(data["name"]))])
#ax.axis('tight')
#ax.legend(loc='upper right')
plt.set_xticklabels(
    [str(x) if x % cval == 0 else "" for x in range(len(data["name"]))])
plt.tight_layout()
plt.legend(Loc='upper right')
plt.savefig(outputplot)
コード例 #8
0
ファイル: run18_SEDS.py プロジェクト: DJRumble/PHD
        plt.loglog(IRAM[:,0],IRAM[:,i]*v(IRAM[:,0]),color='black',marker='o',linestyle='None',markersize=2)
        plt.errorbar(IRAM[:,0],IRAM[:,i]*v(IRAM[:,0]),  yerr=IRAM[:,i+1]*v(IRAM[:,0]),fmt='b.', ecolor='blue')

    #VLA
        plt.loglog(VLA[:,0],VLA[:,i]*v(VLA[:,0]),color='black',marker='o',linestyle='None',markersize=2)
        plt.errorbar(VLA[:,0],VLA[:,i]*v(VLA[:,0]),  yerr=VLA[:,i]*v(VLA[:,0]),fmt='b.', ecolor='blue')

        axes=fig1.gca()
        #axes=fig2.gca()

        cores = [1,2,3,4,7,11,12,17,19,30]
        
        for label in axes.get_xticklabels() + axes.get_yticklabels():
            label.set_fontsize('x-small')

        plt.set_xticklabels('',visible='False',size='x-small')

        if (j == 9):
            plt.set_xlabel(r'$\lambda$ (${\mathrm{\mu m}}$)',size='x-small')
            plt.set_xticklabels('',visible='True',size='x-small')
        if (j == 8):
            plt.set_xlabel(r'$\lambda$ (${\mathrm{\mu m}}$)',size='x-small')
            plt.set_xticklabels('',visible='True',size='x-small')

        if (j % 2):
            plt.set_yticklabels('',visible='True',size='x-small')
        else:
            plt.set_ylabel(r'$\nu$ $S_\nu$ (${\mathrm{Wm^{-1}}}$)',size='x-small')

        plt.axis([1e0,2e3,5e-18,5e-10]) #Large Axis
        plt.text(5e2,5e-11,'FW%s'%(cores[j]),size='x-small')
コード例 #9
0
ファイル: BI.py プロジェクト: Manuste2m/Test
    def Plot(self):
        self.delPlot()
        listSalePlot = []
        listLabel = []
        listDate = []

        tableau20 = [(31, 119, 180), (174, 199, 232), (255, 127, 14), (255, 187, 120),
                     (44, 160, 44), (152, 223, 138), (214, 39, 40), (255, 152, 150),
                     (148, 103, 189), (197, 176, 213), (140, 86, 75), (196, 156, 148),
                     (227, 119, 194), (247, 182, 210), (127, 127, 127), (199, 199, 199),
                     (188, 189, 34), (219, 219, 141), (23, 190, 207), (158, 218, 229)]

        for i in range(len(tableau20)):
            r, g, b = tableau20[i]
            tableau20[i] = (r / 255., g / 255., b / 255.)

        if (len(self.listDimensionsPlot)) == 1 :
            listInDimensions = self.read_CSV_InDimensions(self.listHeadShow[0])
            for i in range(len(listInDimensions)):
                filename = listInDimensions[i]
                listLabel.append(filename)
                ##เพิ่ม Date ตรงนี้
                with open(""+str(self.listDatePlot[0])+str(filename)+str(self.listMeasuresPlot[0])+".csv", newline='') as f:
                    reader = csv.reader(f)
                    row1 = next(reader)
                    row2 = next(reader)
                listSalePlot.append(row2)
            listDate = row1
        elif (len(self.listDimensionsPlot)) == 0:
            for i in range(len(self.listInDimensionsPlot)):
                filename = self.listInDimensionsPlot[i]
                listLabel.append(filename)
                with open(""+str(self.listDatePlot[0])+str(filename)+str(self.listMeasuresPlot[0])+".csv", newline='') as f:
                    reader = csv.reader(f)
                    row1 = next(reader)
                    row2 = next(reader)
                listSalePlot.append(row2)
            listDate = row1
        print (listDate)
        print (listLabel)
        print (listSalePlot)

        canvasPlot = 0
        print (len(self.canvas))
        for plot in range(len(self.plotType)):
            self.canvas.append("canvas"+str(plot))
            if (self.plotType[plot]=="Plot"):
                if (len(self.listMeasuresPlot)==1) and (len(self.listDatePlot)==1):
                    f = Figure(figsize=(6, 5), dpi=80)
                    f.set_facecolor("w")
                    plt = f.add_subplot(111)
                    for i in range(len(listSalePlot)):
                        print (listSalePlot[i])
                        plt.plot(listDate,listSalePlot[i],lw=2.5,color=tableau20[i],label=listLabel[i])
                    minX = (int(min(listDate)))
                    maxX = (int(max(listDate)))
                    x = range(minX, (maxX+1))
                    plt.set_xticks(x)
                    plt.set_xticklabels(listDate)
                    plt.set_title(str(self.listMeasuresPlot[0]))
                    plt.legend(loc='upper left', bbox_to_anchor=(0, 1),ncol=2, fancybox=True, shadow=True)
                    self.canvas[plot] = FigureCanvasTkAgg(f, master=self.f2)
                    self.canvas[plot].show()
                    self.canvas[plot].get_tk_widget().place(x = 300*canvasPlot + 350, y = 10)
                    self.canvas[plot]._tkcanvas.place(x = 300*canvasPlot + 350, y = 10)

            elif (self.plotType[plot]=="Pie"):
                if (len(self.listMeasuresPlot)==1) and (len(self.listDatePlot)==1):
                    f = Figure(figsize=(6, 5), dpi=80)
                    f.set_facecolor("w")
                    plt = f.add_subplot(111)
                    plt.set_title(str(self.listMeasuresPlot[0]))
                    saleCounty = []
                    colors = []
                    for i in range(len(listSalePlot)):
                        saleCountySum = 0
                        colors.append(tableau20[i])
                        for j in range(len(listSalePlot[i])):
                            saleCountySum = saleCountySum + float(listSalePlot[i][j])
                        saleCounty.append(saleCountySum)
                    print (saleCounty)
                    plt.pie(saleCounty, labels=listLabel, colors=colors,
                                autopct='%1.1f%%', shadow=True, startangle=90)
                    plt.axis('equal')
                    self.canvas[plot] = FigureCanvasTkAgg(f, master=self.f2)
                    self.canvas[plot].show()
                    self.canvas[plot].get_tk_widget().place(x = 300*canvasPlot + 350, y = 10)
                    self.canvas[plot]._tkcanvas.place(x = 300*canvasPlot + 350, y = 10)

            elif (self.plotType[plot]=="Bar"):
                if (len(self.listMeasuresPlot)==1) and (len(self.listDatePlot)==1):
                    f = Figure(figsize=(6, 5), dpi=80)
                    f.set_facecolor("w")
                    plt = f.add_subplot(111)

                    print (len(listDate))
                    width = 0.2
                    ind = np.arange(len(listDate))

                    for i in range(len(listSalePlot)):
                        listSalePlot[i] = [float(j) for j in listSalePlot[i]]
                        plt.bar(ind+(i*width),listSalePlot[i],width,color=tableau20[i],label=listLabel[i])
                    plt.set_xticks(ind+((width/2)*(len(listSalePlot))))
                    plt.set_xticklabels(listDate)
                    plt.set_title(str(self.listMeasuresPlot[0]))
                    plt.legend(loc='upper left', bbox_to_anchor=(0, 1),ncol=2, fancybox=True, shadow=True)
                    self.canvas[plot] = FigureCanvasTkAgg(f, master=self.f2)
                    self.canvas[plot].show()
                    self.canvas[plot].get_tk_widget().place(x = 300*canvasPlot + 350, y = 10)
                    self.canvas[plot]._tkcanvas.place(x = 300*canvasPlot + 350, y = 10)
            canvasPlot = canvasPlot + 1.5
            self.plotTypeOlt.append(canvasPlot)
コード例 #10
0
# Change ylim if needed
# plt.ylim(200, 1500) # Samsung
plt.show()

#######################################################################
## LOCATION PROFILE ###################################################

import matplotlib.pyplot as plt
import numpy as np

labels = range(32)

# CHANGE THIS BASED ON THE CHUNK SIZE YOU ARE VISUALIZING FOR
filename = "/mnt/results/loc_profile/8kb.txt"
data_list = []

f = open(filename, 'r')
for line in f:
    data_list.append(float(line))

labels = []
for i in range(32):
    labels.append("{}kb".format(4 * i))

plt.plot(range(32), data_list, 'bo-')
plt.set_xticklabels(labels)

plt.xlabel("Offset Group")
plt.ylabel("Avg. Latency (us)")
plt.show()
コード例 #11
0
#ax = fig.add_subplot(131)

#rects1 = ax.bar(x, stand_alone, width, label='Stand Alone')
#rects1 = ax.bar(x - width/2, stand_alone, width, color='cornflowerblue')
#rects1 = ax.bar(x,time, width)
rects1 = ax.bar(x, read, width, hatch='....', color='white', edgecolor='black')
#rects1 = ax.bar(x - width/2, stand_alone, width, label='Stand Alone')
#rects2 = ax.bar(x, collocated, width, label='Collocated')
#rects2 = ax.bar(x + width/2, collocated, width, color='orange')
#rects2 = ax.bar(x + width/2, collocated, width, label='Collocated')

# Add some text for labels, title and custom x-axis tick labels, etc.
plt.set_ylabel('Traffic in Million', fontsize=12)
plt.set_title('Read', fontsize=14)
plt.set_xticks(x)
plt.set_xticklabels(
    labels,
    fontsize=12,
)
#ax.set_xticklabels(labels, fontsize=12, rotation='vertical')
#ax.legend(loc=1, bbox_to_anchor=(0.5, 0., 0.5, 0.99))
plt.set_yticks(np.arange(0, max(read) + 2, 3))

x = np.arange(len(labels))  # the label locations

fig.subplots_adjust(wspace=.5)
plt.tight_layout()
plt.show()
fig.savefig('method-stream.png', dpi=100)
コード例 #12
0
ファイル: HW6.py プロジェクト: svatozde/DDW-HW6
    print('Done users matrix')

ticks = [0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0]

colours = ['r', 'g', 'b', 'y']
shapes = ['+', 'o', 'x']
print(colours)

with open('pickles/precisions_map.pickle', 'wb') as handle:
    pickle.dump(precisions_map, handle, protocol=pickle.HIGHEST_PROTOCOL)

with open('pickles/super_result.pickle', 'wb') as handle:
    pickle.dump(super_result, handle, protocol=pickle.HIGHEST_PROTOCOL)

fig = plt.figure(figsize=(10, 15))
#fig.subplots_adjust(bottom = 10,  top =20  ,wspace = 50 ,hspace = 50
for i, key in enumerate(precisions_map.keys()):
    plt.plot(ticks,
             precisions_map[key],
             str(colours[i % len(colours)]) + str(shapes[i % 3]),
             label=str(key))

plt.set_xticklabels(ticks)
plt.set_xticks([0.5 * a for a in range(len(ticks))])
plt.set_title('Precision for different distance metrics')
plt.legend(loc='lower left')
plt.grid(axis='both')
plt.savefig('figs/comparsion.jpg')
plt.clf()
plt.cla()
コード例 #13
0
def plot_questions_by_recipient(
    df: pd.DataFrame,
    k: int,
    recipients: List[str] = [],
    question_categories: List[int] = [],
    cluster_labels: Dict = {},
    filename: str = "plot.pdf",
    from_inquiry_only: bool = False,
):
    """
    Plots the kinds of questions RECEIVED by groups
    """
    matched_qas = match_qa_pairs(df, include_group=True)
    matched_qas.drop(["a_cluster"], axis=1, inplace=True)

    if from_inquiry_only:
        matched_qas = matched_qas[matched_qas["group_q"] == "inquiry"]

    if recipients:
        matched_qas = matched_qas[matched_qas["group_a"].isin(recipients)]
        # this doesn't affect pcts so we can do it first

    matched_qas.rename(
        {
            "group_a": "answererCategory",
            "group_q": "questionerCategory",
            "q_cluster": "qCluster",
        },
        axis="columns",
        inplace=True,
    )

    grouped = (matched_qas.groupby(["answererCategory",
                                    "qCluster"]).count().unstack())

    # normalize
    grouped["totals"] = grouped[grouped.columns].sum(axis=1)
    grouped_pct = grouped[grouped.columns].div(grouped.totals, axis=0)

    grouped_pct.drop(["totals"], axis=1, inplace=True)

    # can't drop until after the percents were calculated
    grouped_pct.columns = grouped_pct.columns.droplevel(level=0)

    if question_categories:
        grouped_pct = grouped_pct[question_categories]
        question_labels = question_categories
    else:
        question_labels = list(range(k))

    if cluster_labels:
        legend_labels = [cluster_labels[i] for i in question_labels]
    else:
        legend_labels = question_labels

    formatted_xlabels = [
        "\n".join(wrap(i, 20)) for i in grouped_pct.index.tolist()
    ]

    plt = grouped_pct.plot.bar(stacked=False)
    plt.legend(
        legend_labels,
        title="Question categories",
        loc="upper left",
        bbox_to_anchor=(1.05, 1),
    )
    plt.set_ylabel("Percent of Questions")
    plt.set_xlabel("")
    plt.set_xticklabels(formatted_xlabels)
    plt.figure.savefig(filename, bbox_inches="tight")