Пример #1
0
def Number_by_Source(tweets):

    tweets['statusSource_new'] = ''

    for i in range(len(tweets['statusSource'])):
        m = re.search('(?<=>)(.*)', tweets['statusSource'][i])
        try:
            tweets['statusSource_new'][i] = m.group(0)
        except AttributeError:
            tweets['statusSource_new'][i] = tweets['statusSource'][i]

    # print(tweets['statusSource_new'].head())

    tweets['statusSource_new'] = tweets['statusSource_new'].str.replace('</a>', ' ', case=False)



    tweets['statusSource_new'] = tweets['statusSource_new'].str.replace('</a>', ' ', case=False)
    #print(tweets[['statusSource_new','retweetCount']])

    tweets_by_type= tweets.groupby(['statusSource_new'])['retweetCount'].sum()
    #print(tweets_by_type)

    tweets_by_type.transpose().plot(kind='bar',figsize=(10, 5))
    #plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    plt.title('Number of retweetcount by Source')
    plt._show()
Пример #2
0
def drawLine(f1, f2, feature1TestData, feature2TestData, test_Y, w1, w2, b):
    color = ['grey', 'blue']
    # test_Y += 1

    plt.scatter(feature1TestData,
                feature2TestData,
                c=test_Y,
                cmap=matplotlib.colors.ListedColormap(color))
    plt.xlabel(f1, fontsize=20)
    plt.ylabel(f2, fontsize=20)

    cb = plt.colorbar()

    loc = np.arange(0, max(test_Y), max(test_Y) / float(len(color)))
    cb.set_ticks(loc)
    lbls = le.inverse_transform(np.unique(test_Y))
    cb.set_ticklabels(lbls)

    pointX, pointY = [], []
    x2 = min(feature1TestData) - 5
    x1 = ((-w2 * x2) - b) / w1

    pointX.append(x2)
    pointY.append(x1[0])

    x1 = max(feature1TestData) + 5
    x2 = ((-w1 * x1) - b) / w2

    pointX.append(x1)
    pointY.append(x2[0])

    plt.plot(pointX, pointY, color='green', linewidth=2)

    plt._show()
Пример #3
0
def plot_simplearray(x_array=None,
                     y_array=None,
                     x_label=None,
                     y_label=None,
                     label=None,
                     show=True):
    """
    Plot a simple two dimensional array

    :param x_array: elements of x axis
    :type x_array: tuple
    :param y_array: elements of y axis
    :type y_array: tuple
    :param x_label: x label
    :type x_label: str
    :param y_label: y label
    :type y_label: str
    :param label: label for the entire plot
    :type label: str
    :param show: shot the plot
    :type show: bool
    :return: plot a simple 2d array
    """
    pyplot.plot(x_array, y_array, label=label)
    pyplot.ylabel(y_label)
    pyplot.xlabel(x_label)
    pyplot.legend(loc='upper center', shadow=True)
    if show is True:
        pyplot._show()
Пример #4
0
def step1():
    image = [[255, 7, 3], [212, 240, 4], [218, 216, 230]]

    imageConv = sg.convolve(image, [[1., -1]], mode="valid")
    plt.imshow(imageConv)
    plt._show()
    print(imageConv)
Пример #5
0
def drawLine(f1, f2, feature1TestData, feature2TestData, classTestData, w1, w2,
             b):
    color = ['grey', 'blue']
    classTestData += 1

    plt.scatter(feature1TestData,
                feature2TestData,
                c=classTestData,
                cmap=matplotlib.colors.ListedColormap(color))
    plt.xlabel(f1, fontsize=20)
    plt.ylabel(f2, fontsize=20)

    cb = plt.colorbar()
    loc = np.arange(0, max(classTestData),
                    max(classTestData) / float(len(color)))
    cb.set_ticks(loc)

    lbls = le.inverse_transform(np.unique(classTestData))
    cb.set_ticklabels(lbls)

    # line
    x2 = 2
    x1 = ((-w2 * x2) - b) / w1  # X1, 2
    point1 = [x1, 2]
    x1 = 3
    x2 = ((-w1 * x1) - b) / w2  # 3, X2
    point2 = [3, x2]

    plt.plot(point1, point2, color='red', linewidth=3)

    plt._show()
Пример #6
0
def draw_hist():
    mu = 100
    sigma = 20

    x = mu + sigma * np.random.randn(20000)  # 样本数量
    plt.hist(x, bins=100, color='green',
             normed=True)  # bins:显示有几个直方,normed是否对数据进行标准化

    plt._show()
 def plot_angle_trajectories(self,trajs):
     plt.title("2-D DMP demonstration")
     plt.xlabel("Time(t)")
     plt.ylabel("Angle Position(deg)")
     time = np.arange(0, self.tau + self.dt, self.dt)
     for i in range(0,len(trajs)):
         # plt.plot(time,des_trajs[i])
         plt.plot(time,trajs[i])
         plt._show()
Пример #8
0
def plotdna2(DNA, dyads, nucl, plt_range=500):
    '''
    Plot DNA and show the location of the dyads

    Parameters
    ----------
    DNA : instance of HelixPose
        the DNA to be plotted
    dyads : list
        list of bp indices of the dyads
    plt_range : int, optional
        xyz range (nm), default is 50 nm

      '''

    #plt.close()
    rb_width = 2.0
    rb_width = 2.0
    color = 'kb'

    rb_vec = DNA.rb_vec
    coord = DNA.coord
    NRL = 198
    #NRL = dyads[1]-dyads[0]
    fig = plt.figure()
    ax = p3.Axes3D(fig)
    ax.scatter3D(coord[dyads, 0], coord[dyads, 1], coord[dyads, 2])
    ax.plot3D(coord[:, 0], coord[:, 1], coord[:, 2], color[0] + '-')
    color2 = 'kbgr'
    a = 100
    for d in dyads:
        fixed_frame = np.transpose(DNA.frames[d + nucl.fixed_i[7] - NRL % 2])
        fixed_origin = coord[d + nucl.fixed_i[7] - NRL % 2]
        Q = nuc.of2coords(fixed_origin, fixed_frame)
        P = nuc.of2coords(nucl.coords[nucl.d_index+nucl.fixed_i[7]], \
                            np.transpose(nucl.frames[nucl.d_index+nucl.fixed_i[7]]))
        tf = nuc.get_transformation(P, Q)
        n_coord = nuc.apply_transf_coords(nucl.n_coords, tf)
        for i in range(1, 4):
            ax.plot3D([n_coord[0,0],n_coord[0,0]+a*(n_coord[i,0]-n_coord[0,0])],\
            [n_coord[0,1],n_coord[0,1]+a*(n_coord[i,1]-n_coord[0,1])],\
            [n_coord[0,2],n_coord[0,2]+a*(n_coord[i,2]-n_coord[0,2])], color2[i]+'-')
        ax.scatter3D(coord[nucl.fixed_i + d, 0], coord[nucl.fixed_i + d, 1],
                     coord[nucl.fixed_i + d, 2])

    ax.set_xlabel('X (nm)')
    ax.set_ylabel('Y (nm)')
    ax.set_zlabel('Z (nm)')

    if plt_range is None:
        plt_range = DNA.n_bp * 0.34

    ax.set_xlim3d(-plt_range / 2, plt_range / 2)
    ax.set_ylim3d(-plt_range / 2, plt_range / 2)
    ax.set_zlim3d(0, plt_range)

    plt._show()
Пример #9
0
def plotScatterFigure(X, Y, filename, xlabel, ylabel):

    plt.scatter(X, Y, c="red", alpha=0.5, edgecolors="black")
    plt.title(xlabel + "_VS_" + ylabel)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.savefig(filename)
    plt._show()

    pass
Пример #10
0
def draw_confusion_matrix(y_test, y_predict, c1, c2):

    lbls = []

    if c1 == -1:
        c1Test = y_test[0:20]
        lbls.append("Iris-setosa")
    elif c1 == 0:
        c1Test = y_test[20:40]
        lbls.append("Iris-versicolor")
    elif c1 == 1:
        c1Test = y_test[40:60]
        lbls.append("Iris-virginica")

    if c2 == -1:
        c2Test = y_test[0:20]
        lbls.append("Iris-setosa")
    elif c2 == 0:
        c2Test = y_test[20:40]
        lbls.append("Iris-versicolor")
    elif c2 == 1:
        c2Test = y_test[40:60]
        lbls.append("Iris-virginica")

    desired = np.append(c1Test, c2Test).reshape(40, 1)
    # print("classTest type", type(classTest))
    # print("classTest shape", classTest.shape)
    desired.sort(axis=0)

    # print("desired after sort")
    # print(desired)
    # print("\n\ny predict")
    # print(y_predict)
    # print("type y_predict in fn confusion", type(y_predict[0, 0]))

    confusion = confusion_matrix(desired,
                                 y_predict)  # , labels=["AAAAAAA", "BBBBBB"])
    print("confusion", confusion)
    # print("confusion shape", confusion.shape)
    # print("confusion type", type(confusion))
    #
    # print("lbls")
    # print(lbls)

    df_cm = pd.DataFrame(list(confusion),
                         index=[i for i in lbls],
                         columns=[i for i in lbls])

    # print("\ndf_cm", df_cm)
    # print("df_cm shape", df_cm.shape)
    # print("df_cm type", type(df_cm))

    plt.figure(figsize=(10, 7))
    sn.heatmap(df_cm, annot=True)
    plt._show()
Пример #11
0
def draw_confusion_matrix(y_test, y_predict):
    lbls = ["Iris-setosa", "Iris-versicolor", "Iris-virginica"]

    confusion = confusion_matrix(y_test, y_predict)
    print("Confusion Matrix:")
    print(confusion)

    df_cm = pd.DataFrame(list(confusion), index=[i for i in lbls], columns=[i for i in lbls])

    plt.figure(figsize=(10, 7))
    sn.heatmap(df_cm, annot=True)
    plt._show()
Пример #12
0
def wordcloud_by_province_Demonetization(tweets):
    stopwords = set(STOPWORDS)
    stopwords.add("https")
    stopwords.add("00A0")
    stopwords.add("00BD")
    stopwords.add("00B8")
    stopwords.add("ed")
    stopwords.add("demonetization")
    stopwords.add("Demonetization co")
    stopwords.add("lakh")
    wordcloud = WordCloud(background_color="white",stopwords=stopwords,random_state = 2016).generate(" ".join([i for i in tweets['text_new'].str.upper()]))
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.title("Demonetization")
    plt._show()
Пример #13
0
def Number_by_Source_bis(tweets):
    tweets['statusSource_new2'] = ''

    for i in range(len(tweets['statusSource_new'])):
        if tweets['statusSource_new'][i] not in ['Twitter for Android ','Twitter Web Client ','Twitter for iPhone ']:
            tweets['statusSource_new2'][i] = 'Others'
        else:
            tweets['statusSource_new2'][i] = tweets['statusSource_new'][i]
    #print(tweets['statusSource_new2'])

    tweets_by_type2 = tweets.groupby(['statusSource_new2'])['retweetCount'].sum()



    tweets_by_type2.transpose().plot(kind='pie',figsize=(6.5, 4))
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    plt.title('Number of retweetcount by Source bis')
    plt._show()
Пример #14
0
def wordcloud_by_province_narendramodi(tweets):
    a = pd.DataFrame(tweets['text'].str.contains("narendramodi").astype(int))
    b = list(a[a['text']==1].index.values)
    stopwords = set(STOPWORDS)
    stopwords.add("narendramodi")
    stopwords.add("https")
    stopwords.add("00A0")
    stopwords.add("00BD")
    stopwords.add("00B8")
    stopwords.add("ed")
    stopwords.add("demonetization")
    stopwords.add("Demonetization co")
    stopwords.add("lakh")
    wordcloud = WordCloud(background_color="white",stopwords=stopwords,random_state = 2016).generate(" ".join([i for i in tweets.ix[b,:]['text_new'].str.upper()]))
    plt.imshow(wordcloud)
    plt.axis("off")
    plt.title("Tweets with word 'narendramodi'")
    plt._show()
Пример #15
0
    def PlotGraph(self, hoursAccuracyTuplesList, xlabel, ylabel, classifier, postType):
        import matplotlib.pyplot as plt
        import numpy as np

        accuracies = None
        hourList = []
        for idx, hoursAccuracyTuples in enumerate(hoursAccuracyTuplesList):
            hour, AccuracyListFrom2Fold = hoursAccuracyTuples

            hourList.append(hour)

            if idx == 0:
                accuracies = np.array([AccuracyListFrom2Fold])
            else:
                accuracies = np.concatenate((accuracies, [AccuracyListFrom2Fold]), axis=0)

        averageAccuracies = np.average(accuracies, axis=0)

        indexOfMaxAvg = np.argmax(averageAccuracies)
        kValueForMaxAvg = indexOfMaxAvg + 2

        avgMaxAccuracies = np.array(
            [[accuracies[rowIndex][indexOfMaxAvg] for rowIndex in range(0, len(accuracies))]])
        maxHourIndex = np.argmax(avgMaxAccuracies)

        avgMaxAccuracies = avgMaxAccuracies * 100

        plt.plot(hourList, avgMaxAccuracies[0], c="red")

        plt.axis([0, 28, 30, 100])

        #plt.annotate('Best k-fold value ' + str(kValueForMaxAvg),
        #             xytext=(hourList[maxHourIndex]-3, avgMaxAccuracies[0][maxHourIndex] - 10),

        #             )

        plt.title(classifier + "K = " + str(kValueForMaxAvg) +": "+ xlabel + "_vs_" + ylabel)
        plt.xlabel(xlabel)
        plt.ylabel(ylabel)
        plt.savefig("Images_" + postType +"/"+classifier + "Classifier.png")
        plt._show()
        pass
Пример #16
0
def plot_simplearray(x_array, y_array, x_label, y_label, label, show=True):
    # print label
    # fig, ax = pyplot.subplots()
    pyplot.plot(x_array, y_array, label=label)
    pyplot.ylabel(y_label)
    pyplot.xlabel(x_label)
    # Now add the legend with some customizations.
    pyplot.legend(loc='upper center', shadow=True)
    #
    # # The frame is matplotlib.patches.Rectangle instance surrounding the legend.
    # frame = legend.get_frame()
    # frame.set_facecolor('0.90')
    #
    # # Set the fontsize
    # for label in legend.get_texts():
    #     label.set_fontsize('large')
    #
    # for label in legend.get_lines():
    #     label.set_linewidth(1.5)  # the legend line width
    if show is True:
        pyplot._show()
Пример #17
0
def draw_confusion_matrix(y_test, y_predict, c1, c2):
    lbls = []

    if c1 == -1:
        lbls.append("Iris-setosa")
    elif c1 == 0:
        lbls.append("Iris-versicolor")
    elif c1 == 1:
        lbls.append("Iris-virginica")

    if c2 == -1:
        lbls.append("Iris-setosa")
    elif c2 == 0:
        lbls.append("Iris-versicolor")
    elif c2 == 1:
        lbls.append("Iris-virginica")
    print("y predict", y_predict)
    print(" len y predict", len(y_predict))
    print("y_test", y_test)
    print("y_test", len(y_test))
    confusion = confusion_matrix(y_test, y_predict)
    print("confusion")
    print(confusion)
    #
    # print("lbls")
    # print(lbls)

    df_cm = pd.DataFrame(list(confusion),
                         index=[i for i in lbls],
                         columns=[i for i in lbls])

    # print("\ndf_cm", df_cm)
    # print("df_cm shape", df_cm.shape)
    # print("df_cm type", type(df_cm))

    plt.figure(figsize=(10, 7))
    sn.heatmap(df_cm, annot=True)
    plt._show()
Пример #18
0
plt.pie(y)
plt.title("pie")

plt.subplot(234)
plt.bar(x, y)
plt.title("bar")

# 2D data
import numpy as np
delta = 0.025
x = y = np.arange(-3.0, 3.0, delta)
X, Y = np.meshgrid(x, y)
Z = Y**2 + X**2

plt.subplot(235)
plt.contour(X, Y, Z)
plt.colorbar()
plt.title("contour")

# read image
import matplotlib.image as mpimg
img = mpimg.imread('marvin.jpg')

plt.subplot(236)
plt.imshow(img)
plt.title("imshow")

plt.savefig("matplot_sample.jpg")
plt._show("matplot_sample.jpg")

# Reference : http://www.cnblogs.com/vamei/archive/2013/01/30/2879700.html
Пример #19
0
import matplotlib
matplotlib.use('TkAgg')
matplotlib.get_backend()
matplotlib.get_configdir
import matplotlib.pyplot as plt

plt.plot([1, 2, 3], [5, 6, 7])
plt._show()

#import gensim
#gensim.download()

#import nltk
#nltk.download('averaged_perceptron_tagger')

#from nltk.tokenize import sent_tokenize, word_tokenize

#exapleText='My name is Ujwal Singh. I can Cook food. I can Drive Car. I am a smart guy'
#print(sent_tokenize(exapleText))
#print(word_tokenize(exapleText))
Пример #20
0
def drawIrisData():
    #################x1,X2#################
    x1 = X1_train.append(X1_test)
    x2 = X2_train.append(X2_test)
    label = np.append(labeled_Y_train + 1, labeled_Y_test + 1)
    colors = ['grey', 'blue', 'purple']

    plt.scatter(x1, x2, c=label, cmap=matplotlib.colors.ListedColormap(colors))
    plt.xlabel('X1', fontsize=20)
    plt.ylabel('X2', fontsize=20)

    cb = plt.colorbar()
    loc = np.arange(0, max(label), max(label) / float(len(colors)))
    cb.set_ticks(loc)
    cb.set_ticklabels(['C1-setosa', 'C2-versicolor', 'C3-virginica'])
    plt._show()

    #################x1,X3#################
    x1 = X1_train.append(X1_test)
    x3 = X3_train.append(X3_test)
    label = np.append(labeled_Y_train + 1, labeled_Y_test + 1)
    colors = ['grey', 'blue', 'purple']

    plt.scatter(x1, x3, c=label, cmap=matplotlib.colors.ListedColormap(colors))
    plt.xlabel('X1', fontsize=20)
    plt.ylabel('X3', fontsize=20)

    cb = plt.colorbar()
    loc = np.arange(0, max(label), max(label) / float(len(colors)))
    cb.set_ticks(loc)
    cb.set_ticklabels(['C1-setosa', 'C2-versicolor', 'C3-virginica'])
    plt._show()

    #################x1,X4#################
    x1 = X1_train.append(X1_test)
    x4 = X4_train.append(X4_test)
    label = np.append(labeled_Y_train + 1, labeled_Y_test + 1)
    colors = ['grey', 'blue', 'purple']

    plt.scatter(x1, x4, c=label, cmap=matplotlib.colors.ListedColormap(colors))
    plt.xlabel('X1', fontsize=20)
    plt.ylabel('X4', fontsize=20)

    cb = plt.colorbar()
    loc = np.arange(0, max(label), max(label) / float(len(colors)))
    cb.set_ticks(loc)
    cb.set_ticklabels(['C1-setosa', 'C2-versicolor', 'C3-virginica'])
    plt._show()

    #################x2,X3#################
    x2 = X2_train.append(X2_test)
    x3 = X3_train.append(X3_test)
    label = np.append(labeled_Y_train + 1, labeled_Y_test + 1)
    colors = ['grey', 'blue', 'purple']

    plt.scatter(x2, x3, c=label, cmap=matplotlib.colors.ListedColormap(colors))
    plt.xlabel('X2', fontsize=20)
    plt.ylabel('X3', fontsize=20)

    cb = plt.colorbar()
    loc = np.arange(0, max(label), max(label) / float(len(colors)))
    cb.set_ticks(loc)
    cb.set_ticklabels(['C1-setosa', 'C2-versicolor', 'C3-virginica'])
    plt._show()

    #################x2,X4#################
    x2 = X2_train.append(X2_test)
    x4 = X4_train.append(X4_test)
    label = np.append(labeled_Y_train + 1, labeled_Y_test + 1)
    colors = ['grey', 'blue', 'purple']

    plt.scatter(x2, x4, c=label, cmap=matplotlib.colors.ListedColormap(colors))
    plt.xlabel('X2', fontsize=20)
    plt.ylabel('X4', fontsize=20)

    cb = plt.colorbar()
    loc = np.arange(0, max(label), max(label) / float(len(colors)))
    cb.set_ticks(loc)
    cb.set_ticklabels(['C1-setosa', 'C2-versicolor', 'C3-virginica'])
    plt._show()

    #################x3,X4#################
    x3 = X3_train.append(X3_test)
    x4 = X4_train.append(X4_test)
    label = np.append(labeled_Y_train + 1, labeled_Y_test + 1)
    colors = ['grey', 'blue', 'purple']

    plt.scatter(x3, x4, c=label, cmap=matplotlib.colors.ListedColormap(colors))
    plt.xlabel('X3', fontsize=20)
    plt.ylabel('X4', fontsize=20)

    cb = plt.colorbar()
    loc = np.arange(0, max(label), max(label) / float(len(colors)))
    cb.set_ticks(loc)
    cb.set_ticklabels(['C1-setosa', 'C2-versicolor', 'C3-virginica'])
    plt._show()
Пример #21
0
 def __pyplot_show(*args, **kwargs):
     return pyplot._show(*args, **kwargs)
Пример #22
0
def plotvlines(cdfdata, labels, filename,gfolder, xlabel='',ylabel='', islog=False,figwidth=6, figlen=4, resolution=0.0001, neglect=[], showlen=False,colors=True, legendposition = 'lower right', title =None,xlimit=None,topdata=None, mindatalen = 1,extension='.pdf',xrange=None):
	return
	fig = plt.figure(figsize=(figwidth,figlen))
	plt.axvline(x=5, ymax=10)
	plt.axvline(x=10, ymax=100)
	plt.axvline(x=0, ymax=5)
	plt.show()
	plt.ylim([0,100])
	empty = True
	markervalues = ['*','o','.']#,'_', '^','x','s','v', '<', '>', '1', '2', '3', '4', '8', 's', 'p', 'D', 'd', '_' ]
	colorvalues = ['b','g', 'r', 'k', 'y', 'm', 'c','#CCCCCC', '#808080']
	dashes = [[]]#[3,3,3,3], [],[3, 3, 3, 3], [], [3, 3, 3, 3], [5, 1, 5, 1]]
	leng = 0
	maxx = 0
	try:
		if topdata != None:
			mindatalen = min(sorted([len(x) for x in cdfdata], reverse=True)[:topdata])
	except:
		mindatalen = 1
	i = 0
	numdata = len(labels)
	for v in range(len(labels)):
		vindex = v
		color = colorvalues[v%len(colorvalues)]
		if topdata != None:
			color = colorvalues[i%len(colorvalues)]
		marker = markervalues[v%len(markervalues)]
		dash = dashes[v%len(dashes)]
		label = labels[v]
		dat = cdfdata[v]
		i+=1
		#try:
		for d in dat:
			print dat.index(d)*numdata+vindex,d
			plt.axvline(x=d, ymax=float(d/max(dat)))
			continue
			plt.axvline(x=dat.index(d)*numdata+vindex,ymin=0,ymax=d, color=color)
			#, label=label,color=color,dashes=dash)#, marker=marker)#, dashes=dash)#+'('+str(len(data))+')'
		#except:
		#pass
	#plt.legend(loc=legendposition, fontsize=10)
	if xlimit != None:
	 	plt.xlim(xlimit)
	if xrange != 0:
		plt.xlim(xrange)
	def setFigLinesBW(fig):
		"""
		Take each axes in the figure, and for each line in the axes, make the
		line viewable in black and white.
		"""
		for ax in fig.get_axes():
			setAxLinesBW(ax)
	if not colors:
		setFigLinesBW(fig)
	plt.locator_params(nbins=5, axis='x')
	if title != None:
		plt.title(title)
	plt.ylabel(ylabel)
	plt.xlabel(xlabel)
	title = filename.replace(' ','')
	if islog:
		plt.gca().set_xscale('log')
	plt.tight_layout()
	plt.savefig(gfolder+'/'+title+extension)
	plt._show()
	plt.close()
Пример #23
0
import matplotlib
import matplotlib.pyplot as pt
import numpy as np
from mpl_toolkits.mplot3d import axes3d

fig = pt.figure()
chart = fig.add_subplot(1, 1, 1, projection='3d')
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
y = [1, 2, 3, 5, 7, 9, 3, 2, 1, 0]
z = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
dx = np.ones(10)
dy = np.ones(10)
dz = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

chart.set_xlabel("X axis")
chart.set_ylabel('Y axis')
chart.set_zlabel('Z axis')

chart.bar3d(x, y, z, dx, dy, dz, color="red")

pt._show()
def CreateFigures(LTM=10):
    urk = np.loadtxt('SolutionDet.txt')
    ussls = np.loadtxt('SolutionSto.txt')
    uas = np.loadtxt('SolutionStoAs.txt')
    t= ussls[:,0]
    #Pots Vs Time
    plt.close()
    w=1.0
    fig_width_pt =538.58*w                   # Get this from LaTeX using \showthe\columnwidth(190mm)
    inches_per_pt = 1.0/72.27                # Convert pt to inch
    golden_mean = (np.sqrt(5) - 1.0) / 2.0   # Aesthetic ratio
    fig_width = fig_width_pt * inches_per_pt # width in inches
    fig_height = fig_width*golden_mean       # height in inches
    fig_size =  [fig_width, fig_height]
    params = {'backend': 'ps',
        'axes.labelsize': 10,
        'text.fontsize': 10,
        'legend.fontsize': 8,
        'xtick.labelsize': 8,
        'ytick.labelsize': 8,
        'text.usetex': True,
        'figure.figsize': fig_size}
    rcParams.update(params)
    
##
    fig1, ax1 = plt.subplots()
    #plt.title('Jerez-Chen Model Experimental Parameters')
    OC_line = mlines.Line2D([], [], color='#000000', linestyle='-', lw=2, marker='',  markersize=1)
    OB_line = mlines.Line2D([], [], color='#666666', linestyle='-', lw=2, marker='',  markersize=1)
    sOC_line = mlines.Line2D([], [], color='#666666', linestyle='-.', lw=4, marker='', markersize=1)
    sOB_line = mlines.Line2D([], [], color='#000000', linestyle='-.', lw=4, marker='', markersize=1)
#
    ax1.plot(urk[:, 0], urk[:, 1],
             color='#000000',
             linestyle='-',
             lw=2,
             marker='',
             label='osteoclast'
    )
    ax1.plot(ussls[:, 0], ussls[:, 1],
             color='#666666', 
             linestyle='-.', 
             lw=3,
             marker='',
             label='Sto osteoclast'
    )
    ax1.set_xlabel('time (days)')
    ax1.set_ylabel('OCs (u1)', color='k')
    ax2 = ax1.twinx()
    #
    ax2.plot(urk[:, 0], urk[:, 2],
             color='#666666',
             lw = 2,
             linestyle='-',
             marker='',
             label='osteoblast'
    )
    ax2.plot(ussls[:, 0], ussls[:, 2],
             color='#000000',
             linestyle='-.',
             lw=3,
             marker='',
             label='Sto osteoblast'
    )
    ax2.set_xlabel('time (days)')
    ax2.set_ylabel(r'OBs (u2)')
    ax2.grid(True)
    plt.legend([OC_line, OB_line, sOC_line, sOB_line],
               ["OCs", "OBs", "stoOCs", "stoOBs"],
               bbox_to_anchor=(0., 1.02, 1., .5), 
               loc=3,
               ncol=4, 
               mode="expand",
               borderaxespad=0.
    )
    plt.savefig("CellsTime.eps")
    plt._show()
    #   
    #
    #Phase Potrait
    fig1, ax3 = plt.subplots()
    #plt.title('Stochastic Power Law Bone Remodeling')
    ax3.set_xlim(-1, 13)
    ax3.set_ylim(-50, urk[:,2].max()*1.15)
    ax3.plot(urk[:, 1], urk[:, 2],
             color='#000000',
             linestyle='-',
             lw=3,
             label='Deterministic'
    )
    ax3.plot(StoPlbrmJC.Ubar[0], StoPlbrmJC.Ubar[1],
             'o',
             mfc='none',
             ms=8,
             #label=r'$\bar{u}$'
    )
    ax3.plot(StoPlbrmJC.Uzero[0], StoPlbrmJC.Uzero[1],
             's', 
             mfc='#666666',
             ms=8
    )
    ax3.plot(ussls[:, 1], ussls[:, 2],
             color='#666666', 
             ms=1,
             label='Stochastic Short Time'
    )
    ax3.plot(uas[:, 1], uas[:, 2],
             color='#666666',
             lw=1,
             linestyle='-.',
             label='Long Time Stochastic')
    #ax3.plot(uas[0,0], uas[0,1], 'x', mfc='green', ms=12)
    ax3.set_xlabel(r'$u_1$')
    ax3.set_ylabel(r'$u_2$')
    ax3.grid(True)
    ax3.legend(loc=0)
    plt.savefig("PhasePotrait.eps")
    plt.show()
   #
   #
    fig = plt.figure()
    #ax = fig.gca(projection='3d')
    ax = Axes3D(fig)
    ax.set_xlabel(r'$u_1$')
    ax.set_ylabel(r'$t$')
    ax.set_zlabel(r'$u_2$')
    ax.view_init(elev=20., azim=195)
    #
    ax.plot(urk[:, 1], t, urk[:, 2],
            color='#000000',
            lw=1,
            linestyle='-',
            label='Deterministic'
    )
    ax.plot(ussls[:, 1], t, ussls[:, 2],
            color='#666666',
            lw=1,
            linestyle='-',
            #label='Sto Short Time'
    )
    ax.plot(urk[:, 1], LTM*t[-1]+t, urk[:, 2],
            color='#000000',
            lw=1,
            linestyle='-',
            #label='Det Long Time'
    )
    ax.plot(uas[:, 1], LTM*t[-1]+t, uas[:, 2],
            color='#666666',
            lw=1,
            linestyle='-',
            label='Stochastic'
    )
    ax.legend()
    plt.savefig("PhasePotrait3d.eps")
    plt.show()
Пример #25
0
        nsamp=[90,90,90,90,90,90,90,699]
        ncancer=[0,2,1,5,2,3,6,9]
        dose=[0,1,2,4,1,2,4,0]

    if (False):
        #all schwannomas in males, no control
        nsamp=[90,90,90,90,90,90,90]
        ncancer=[3,3,5,7,4,4,7]
        dose=[0,1,2,4,1,2,4]


    param_guess=numpy.asarray([0.03,0.03])
    step_size=numpy.asarray([0.01,0.01])
    mychain=run_chain(param_guess,20000,step_size,nsamp,ncancer,dose)





    plt.clf()

    plt.plot(mychain[:, 0], mychain[:, 1], ".")

    ax = plt.gca()

    ax.set_yscale("log")
    ax.set_xscale("log")

    plt._show()