Ejemplo n.º 1
0
def radar_plot():
    """
    radar plot
    """
    # 生成测试数据
    labels = np.array(["A组", "B组", "C组", "D组", "E组", "F组"])
    data = np.array([68, 83, 90, 77, 89, 73])
    theta = np.linspace(0, 2 * np.pi, len(data), endpoint=False)

    # 数据预处理
    data = np.concatenate((data, [data[0]]))
    theta = np.concatenate((theta, [theta[0]]))

    # 画图方式
    plt.subplot(111, polar=True)
    plt.title("雷达图", fontproperties=myfont)

    # 设置"theta grid"/"radar grid"
    plt.thetagrids(theta * (180 / np.pi), labels=labels, fontproperties=myfont)
    plt.rgrids(np.arange(20, 100, 20), labels=np.arange(20, 100, 20), angle=0)
    plt.ylim(0, 100)

    # 画雷达图,并填充雷达图内部区域
    plt.plot(theta, data, "bo-", linewidth=2)
    plt.fill(theta, data, color="red", alpha=0.25)

    # 图形显示
    plt.show()
    return
def stereoProjPlot(phi, psi, int=None, lineSpec='', titleText=None, maxPsi=90, fig=None, partPlot=False, thetaStep=None,
		rStep=None, rMax=None, cbarOri='vertical'):
	# only allow defined psi values
	phi = phi[(psi >= -maxPsi) & (psi <= maxPsi)]
	if int is not None:
		int = int[(psi >= 0) & (psi <= maxPsi)]
	psi = psi[(psi >= 0) & (psi <= maxPsi)]
	#h = polarplot(np.deg2rad(phi),tand(0.5 * psi),lineSpec)
	if fig is None:
		fig = plt.figure()
	ax = fig.add_subplot(111, projection='polar')
	if int is None:
		#c = ax.scatter(np.deg2rad(phi), bc.tand(0.5 * psi))
		if len(lineSpec) > 0:
			c = plt.polar(np.deg2rad(phi), bc.tand(0.5 * psi), lineSpec)
		else:
			c = plt.polar(np.deg2rad(phi), bc.tand(0.5 * psi))
	else:
		c = ax.scatter(np.deg2rad(phi), bc.tand(0.5 * psi), c = int, cmap='jet')
		fig.colorbar(c, orientation=cbarOri)
	if thetaStep is not None:
		plt.thetagrids(np.array(range(0, 360, thetaStep)))
	if rMax is not None and rStep is not None:
		plt.rgrids(np.array(range(0, rMax, rStep)))
	if not partPlot:
		c[0].axes.set_ylim(0, 1)
	if titleText is not None:
		ax.set_title(titleText)
	plt.tight_layout()  # layout without overlapping
	plt.show()
	return fig, c, ax
Ejemplo n.º 3
0
def plot_chart(values: List, angles: List, title: str) -> None:
    _, ax = plt.subplots(figsize=(6, 6), subplot_kw=dict(polar=True))
    plt.thetagrids(range(0, 360, 45), ("E", "NE", "N", "NW", "W", "SW", "S", "SE"))
    ax.plot(angles, values, color="violet", linewidth=2)
    ax.fill(angles, values, "b", alpha=0.1)
    plt.title(title)
    plt.show()
Ejemplo n.º 4
0
 def radar_chart(data1, data2, i):
     # 1931年
     data_radar1 = np.array(data1) # 数据
     angles1 = np.linspace(0, 2*np.pi, labels_length, endpoint=False)  # 分割圆周长
     data_radar1 = np.concatenate((data_radar1, [data_radar1[0]]))  # 闭合
     angles1 = np.concatenate((angles1, [angles1[0]]))  # 闭合
     # 1932年
     data_radar2 = np.array(data2) # 数据
     angles2 = np.linspace(0, 2*np.pi, labels_length, endpoint=False)  # 分割圆周长
     data_radar2 = np.concatenate((data_radar2, [data_radar2[0]]))  # 闭合
     angles2 = np.concatenate((angles2, [angles2[0]]))  # 闭合
     # 做极坐标系1931
     plt.polar(angles1, data_radar1, 'bo-', linewidth=1)
     # 做极坐标系1932
     plt.polar(angles2, data_radar2, 'go-', linewidth=1)
     # 填充1931
     plt.fill(angles1, data_radar1, facecolor='r', alpha=0.7)#
     # 填充1932
     plt.fill(angles2, data_radar2, facecolor='y', alpha=0.7)
     plt.thetagrids(angles1 * 180/np.pi, labels)  # 做标签
     plt.ylim(0, 71)
     plt.legend(['1931', '1932'])
     # 保存图片
     name = "radar/"+sites[i]+".png"
     save_picture(plt, name, title=sites[i])
def showpower(user_id):
    value_of_string = powervalue(data[user_id]["cases"], "字符串")
    value_of_lineartable = powervalue(data[user_id]["cases"], "线性表")
    value_of_array = powervalue(data[user_id]["cases"], "数组")
    value_of_searchalgorithm = powervalue(data[user_id]["cases"], "查找算法")
    value_of_sigitaloperation = powervalue(data[user_id]["cases"], "数字操作")
    value_of_treestructure = powervalue(data[user_id]["cases"], "树结构")
    value_of_graphstructure = powervalue(data[user_id]["cases"], "图结构")
    value_of_sortingalgorithm = powervalue(data[user_id]["cases"], "排序算法")
    matplotlib.rcParams['font.family'] = 'SimHei'
    matplotlib.rcParams['font.sans-serif'] = ['SimHei']
    lables = np.array(
        ["字符串", "线性表", "数组", "查找算法", "数字操作", "树结构", "图结构", "排序算法"])
    nAttr = 8
    date = np.array([
        value_of_string, value_of_lineartable, value_of_array,
        value_of_searchalgorithm, value_of_sigitaloperation,
        value_of_treestructure, value_of_graphstructure,
        value_of_sortingalgorithm
    ])
    angles = np.linspace(0, 2 * np.pi, nAttr, endpoint=False)
    date = np.concatenate((date, [date[0]]))
    angles = np.concatenate((angles, [angles[0]]))
    fig = plt.figure(facecolor="white")
    plt.subplot(111, polar=True)
    plt.plot(angles, date, 'bo-', color='g', linewidth=2)
    plt.fill(angles, date, facecolor='g', alpha=0.25)
    plt.thetagrids(angles * 180 / np.pi, lables)
    plt.figtext(0.52, 0.95, 'python编程能力值雷达图', ha='center')
    plt.grid(True)
    plt.savefig('python_radar.JPG')
    plt.show()
Ejemplo n.º 6
0
    def plot_list(points, primes=False, labels=False, file_name=""):
        max_len = 0
        for pt in points:
            length, angle = pt.polar_form()

            if (length > max_len):
                max_len = length

            r = pt.real
            i = pt.imaginary

            if pt.is_prime():
                plt.polar(angle, length, 'ro')
            else:
                plt.polar(angle, length, 'bo')
            if (labels):
                plt.text(angle,
                         length,
                         str(multiple),
                         horizontalalignment='center',
                         verticalalignment='bottom')

        plt.thetagrids(range(0, 360, 60),
                       ('1', '1+ω', 'ω', '-1', '-ω-1', '-ω'))
        plt.rgrids(np.arange(0, max_len, max_len / 10), labels=[])

        if file_name != "":
            plt.savefig(file_name)
            plt.clf()
        else:
            plt.show()

        return plt
Ejemplo n.º 7
0
def radar_plot():
    """
    radar plot
    """
    # 生成测试数据
    labels = np.array(["A组", "B组", "C组", "D组", "E组", "F组"])
    data = np.array([68, 83, 90, 77, 89, 73])
    theta = np.linspace(0, 2*np.pi, len(data), endpoint=False)

    # 数据预处理
    data = np.concatenate((data, [data[0]]))
    theta = np.concatenate((theta, [theta[0]]))

    # 画图方式
    plt.subplot(111, polar=True)
    plt.title("雷达图", fontproperties=myfont)

    # 设置"theta grid"/"radar grid"
    plt.thetagrids(theta*(180/np.pi), labels=labels, fontproperties=myfont)
    plt.rgrids(np.arange(20, 100, 20), labels=np.arange(20, 100, 20), angle=0)
    plt.ylim(0, 100)

    # 画雷达图,并填充雷达图内部区域
    plt.plot(theta, data, "bo-", linewidth=2)
    plt.fill(theta, data, color="red", alpha=0.25)

    # 图形显示
    plt.show()
    return
Ejemplo n.º 8
0
def spiderplot(toplot, Name, frequencies):
    toplot['outcome'] = outcome
    toplot['group'] = group

    Nonreco_all = (toplot[toplot.outcome == 1])[frequencies]
    Reco_all = (toplot[toplot.outcome == 0])[frequencies]

    Reco = np.mean(Reco_all)
    Nonreco = np.mean(Nonreco_all)

    Nonreco = [*Nonreco, Nonreco[0]]
    Reco = [*Reco, Reco[0]]
    frequencies = [*frequencies, frequencies[0]]

    Nonreco_all = Nonreco_all[frequencies]
    Reco_all = Reco_all[frequencies]

    label_loc = np.linspace(start=0, stop=2 * np.pi, num=5)

    fig = plt.figure(figsize=(8, 8))
    plt.subplot(polar=True)
    plt.plot(label_loc, Reco, label='Recovered')
    plt.fill(label_loc, Reco, 'skyblue', alpha=0.4)
    for i in range(0, len(Reco_all)):
        plt.scatter(label_loc, Reco_all.iloc[i], c='blue')
    plt.plot(label_loc, Nonreco, label='Non-Recovered')
    plt.fill(label_loc, Nonreco, 'orange', alpha=0.3)
    for i in range(0, len(Nonreco_all)):
        plt.scatter(label_loc, Nonreco_all.iloc[i], c='orange')
    plt.title(Name, size=20, y=1.05)
    plt.thetagrids(np.degrees(label_loc), labels=frequencies)
    plt.legend()
    pdf.savefig(fig)
    plt.close()
Ejemplo n.º 9
0
def radar_plot(data=[],
               title='Radar Graph',
               radar_labels=[
                   'dimension1', 'dimension2', 'dimension3', 'dimension4',
                   'dimension5'
               ],
               figsize=(6, 6),
               fontsize=15):
    """

    Args:
        data: List of data
        title: the name of the graph
        radar_labels: the name of each dimension
        figsize: figsize
        fontsize: fontsize
    Returns:

    """
    angles = np.linspace(0, 2 * np.pi, len(radar_labels), endpoint=False)
    fig = plt.figure(figsize=figsize, facecolor="white")
    plt.subplot(111, polar=True)
    plt.ylim(0, 1)
    plt.plot(angles, data, 'o-', linewidth=1, alpha=0.2)
    plt.fill(angles, data, alpha=0.25)
    plt.thetagrids(angles * 180 / np.pi, radar_labels, fontsize=fontsize)
    plt.figtext(0.52, 0.95, title, ha='center', size=25)
    # plt.setp(legend.get_texts(), fontsize='large')
    plt.grid(True)
    # plt.savefig('holland_radar.jpg')
    plt.show()
Ejemplo n.º 10
0
    def _create_plot(self, theta, r, data, data_cclw, ep, reward, direction):
        """
        Create a polar projection.
        """

        fig_left = plt.subplot(1, 2, 1, projection="polar")
        fig_left.set_title('Clockwise')
        plt.thetagrids([theta * 15 for theta in range(360 // 15)])
        fig_left.pcolormesh(theta, r, data.T, cmap='RdBu')

        fig_right = plt.subplot(1, 2, 2, projection="polar")
        fig_right.set_title('Counterclockwise')
        plt.thetagrids([theta * 15 for theta in range(360 // 15)])
        fig_right.pcolormesh(theta, r, data_cclw.T, cmap='RdBu')

        plt.tight_layout()
        plt.suptitle('Policy in episode {} with reward {}'.format(ep, reward))

        # fig_right.set_title('Policy ({}) in episode {} with reward {}'.format(direction, ep, reward))
        # plt.plot()
        # fig.set_theta_zero_location("N")

        # plt.thetagrids([theta * 15 for theta in range(360//15)])
        # plt.rgrids([.1 * _ for _ in range(1, 2*self.max_r)])
        return plt.plot()
Ejemplo n.º 11
0
def plt_radar(labels, data, algorithm, title=None, legend=None, save=False):
    num_labels = len(labels)
    num_data = data.shape[0]
    angles = np.linspace(0, 2 * np.pi, num_labels, endpoint=False)

    num_algorithm = data.shape[1]
    current_data = np.zeros((num_data, num_algorithm + 1))

    for i in range(num_data):
        current_data[i] = np.concatenate((data[i], [data[i][0]]))

    angles = np.concatenate((angles, [angles[0]]))
    labels = np.concatenate((labels, [labels[0]]))

    for i in range(num_data):
        plt.polar(angles, current_data[i], 'o-', linewidth=1, label='$' + algorithm[i] + '$')
        plt.fill(angles, current_data[i], alpha=0.25)

    plt.thetagrids(angles * 180 / np.pi, labels)

    if title is not None:
        plt.title('$' + title + '$')
    if legend is not None:
        plt.legend(bbox_to_anchor=(legend))

    if save is not False:
        plt.savefig(save[0], dpi=save[1], bbox_inches='tight')

    plt.show()
Ejemplo n.º 12
0
 def draw(self, district=6,aDay='20170304'):
     path = 'config/pieChart/' + dis[district] + aDay + '.json'
     with open(path) as json_file:
         daydata = json.load(json_file)
     plt.sca(self.ax)
     radii = list(daydata.values())
     textlist = list(daydata.keys())
     maxval = max(radii)
     lenth = len(str(maxval))
     if lenth == 5:
         multiple = 1000
     elif lenth == 4:
         multiple = 100
     elif lenth == 3:
         multiple = 10
     else:
         multiple = 1
     for i in range(24):
         if i < len(radii):
             radii[i] /=multiple
         else:
             radii.append(0)
     theta1 = []
     for i in self.theta:
         theta1.append(i / 180 * np.pi)
     self.barColor(textlist)
     plt.cla()
     self.bars = self.ax.bar(theta1, radii, width=np.pi / 12, bottom=0.0,color=self.colorlist,alpha=0.5)
     danwei = '单位:' + str(multiple) + '条'
     plt.thetagrids(self.thetalist, textlist)
     self.ax.set_rlabel_position('-90')  # 坐标位置
     plt.text(-np.pi*0.25, maxval/multiple*1.68, danwei, fontsize=16)
Ejemplo n.º 13
0
def radar_plot():
    """
    radar plot
    """
    # 生成测试数据
    labels = np.array(["A", "B", "C", "D", "E", "F"])
    data = np.array([38, 43, 90, 67, 89, 73])
    theta = np.linspace(0, 2 * np.pi, len(data), endpoint=False)

    # 数据预处理
    data = np.concatenate((data, [data[0]]))
    theta = np.concatenate((theta, [theta[0]]))

    # 画图方式
    plt.subplot(111, polar=True)

    # 设置"theta grid"/"radar grid"
    plt.thetagrids(theta * (180 / np.pi), labels=labels)
    plt.rgrids(np.arange(20, 101, 20), labels=np.arange(20, 101, 20), angle=0)
    plt.ylim(0, 100)

    # 画雷达图,并填充雷达图内部区域
    plt.plot(theta, data, "bo-", linewidth=2)
    plt.fill(theta, data, color="red", alpha=0.25)

    # 图形显示
    plt.show()
    return
Ejemplo n.º 14
0
def single(multiple, total_num):
    fig = plt.figure(0, figsize=(10, 10))
    fig.show()
    """theta's, r's"""
    plt.polar([i * np.pi * 2 / total_num for i in range(total_num + 1)],
              [1] * (total_num + 1),
              c=(1, 0, 0))

    plt.thetagrids([None])
    plt.rgrids([30])
    plt.autoscale(False)

    for i in range(1, total_num + 1):
        plt.polar((i * np.pi * 2 / total_num,
                   ((i * multiple) % total_num) * np.pi * 2 / total_num),
                  [1] * 2,
                  c=(0, 0, 0))

        with plt.xkcd(randomness=0):
            plt.annotate(i,
                         xy=(i * np.pi * 2 / total_num, 1.05),
                         horizontalalignment='center',
                         verticalalignment='center')

    plt.show()
Ejemplo n.º 15
0
def figure_init():
    plt.close()
    fig = plt.figure(figsize=(6, 6))
    ax = plt.subplot(polar=True)
    ax.patch.set_alpha(0)
    fig.patch.set_alpha(0)
    ax.set_rlabel_position(45)
    plt.thetagrids(np.arange(0, 360, 30), size=10)
    ax.spines['polar'].set_visible(False)
    ax.grid(linestyle=':', alpha=0.6, linewidth=2, color='black')
    return fig, ax
    def add_axis(self, fig, subplot):
        ax = fig.add_subplot(subplot, polar=True)

        # Set up ticks and labels
        self.r_ticks = range(self.r0, self.r0 + (self.nrange+1) * self.dr, self.dr)
        self.theta_ticks = [self.theta0 + self.dtheta * b for b in range(self.nbeam+1)]
        rlabels = [""] * len(self.r_ticks)
        for i in range(0, len(rlabels), 5):
            rlabels[i] = i
        plt.rgrids(self.r_ticks, rlabels)
        plt.thetagrids(self.theta_ticks, range(self.nbeam))
        return ax
Ejemplo n.º 17
0
def initialisation_graphe(ondes,enonce=True):
    plt.clf()            # Nettoyage, on commence un nouveau graphe
    plt.axes(polar=True) # On initie un graphe en polaires
    # Puis on définit le titre
    if enonce: titre = 'Enonce: Sommer '
    else     : titre = 'Corrige: Sommer '
    titre += ", ".join(['${}$'.format(o) for o in ondes[:-1]])
    titre += " et ${}$.".format(ondes[-1])
    plt.title(titre)
    # et finalement les grilles en distances
    plt.rgrids([i+1 for i in range(max_size)])
    plt.thetagrids([i*15 for i in range(360//15)]) # et en angles
Ejemplo n.º 18
0
def doPlot(values, degrees):
    plt.axes(polar=True)
    plt.polar(degrees,
              values,
              linestyle='solid',
              linewidth=1.5,
              color='blue',
              marker='.',
              markersize=2.0,
              markeredgecolor='red',
              markeredgewidth=0.5)
    plt.thetagrids([0.0, 90.0, 180.0, 270.0])
    plt.show()
Ejemplo n.º 19
0
    def radar_many(self, label, df, name, istype, live):
        matplotlib.rcParams['font.family'] = 'SimHei'  # 将绘图区域设置成中文字符
        radar_labels = np.array(label)  # 雷达标签
        nAttr = 7
        result = []
        for i in range(2):
            player = df[df[0] == name[i]]
            eachdata = []
            if not player.empty:
                print(player)
            else:
                list2 = [[name[i], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]
                player = pd.DataFrame(list2, columns=[0, 1, 2, 3, 4, 5, 6, 7])
                print(player)

            for i in range(1, player.shape[1]):
                eachdata.append(list(player[i]))
            eachdata.append(list(player[1]))
            print(eachdata)
            result.append(eachdata)
        #     =[[scoreratio[1]],[assistratio[1]],[reboundratio[1]],[stealratio[1]],[blockratio[1]],[hit_percentageratio[1]],[three_percentageratio[1]],[scoreratio[1]]]
        angles = np.linspace(0, 2 * np.pi, nAttr, endpoint=False)
        angles = np.concatenate(
            (angles, [angles[0]
                      ]))  # 将angles[0]以行的形式添加到angles的最下方,在末尾添加第一行是为了画出的图形能闭合
        plt.figure(facecolor="white")  # 设置画布的底色(除雷达突然以外的画布)
        ax = plt.subplot(111, polar=True)  # 将画框设置成圆形雷达图案
        ax.set_rgrids(np.arange(0, 1.2, 0.2),
                      '-')  # 加了这一行后,一定要设置'-',a就没了网格线上的数字了(0.2-1.0)
        plt.plot(angles, result[0], 'o-', linewidth=1,
                 alpha=0.3)  # 设置七芒星图案角上的点,alpha为控制透明度
        plt.fill(angles, result[0], alpha=0.4)  # 填充七芒星图案
        plt.plot(angles, result[1], 'o-', linewidth=1,
                 alpha=0.3)  # 设置七芒星图案角上的点,alpha为控制透明度
        plt.fill(angles, result[1], alpha=0.4)  # 填充七芒星图案
        plt.thetagrids(angles * 180 / np.pi, radar_labels)  # 设置雷达七角上标签
        plt.figtext(0.5, 1, name, ha='center',
                    size=20)  # figtext加入文本框,前面两个数字代表位置
        plt.figtext(0.5,
                    0,
                    '{}{}{}{}能力对比的能力图'.format(name[0], name[0], istype, live),
                    ha='center',
                    size=15,
                    color='blue')
        legend = plt.legend(name, loc=(0.94, 0.80), labelspacing=0.1)
        plt.grid(True)
        plt.show()
        sio = BytesIO()
        plt.savefig(sio, format='png')
        plt.close()
        return sio
Ejemplo n.º 20
0
    def plot_polygon_radar_chart(self, titles, data):
        plt.figure(figsize=(10, 6))  # 设置图形大小
        ax = plt.subplot(polar=True)  # 设置图形为极坐标图

        # 设置网格,标签
        plt.thetagrids(range(0, 360, int(360 / len(titles))), titles)
        theta = np.linspace(0, 2 * np.pi, len(data[[*data][0]]))  # 根据index1的数量将圆均分
        max_value = 0  # 寻找数值中最大的那个

        # 绘制图形, 这里必须放到前面,不然legend就不对
        for key in data.keys():
            # 绘制图形
            max_value = max(max_value, max(data[key]))
            ax.plot(theta, data[key], 'o-', linewidth=1)  # 绘制线段
            plt.fill(theta, data[key], alpha=0.5)  # 设置颜色与透明度
            # 绘制数据标签
            for a, b in zip(theta, data[key]):
                ax.text(a, b + 5, '%.00f' % b, ha='center', va='center', fontsize=10, color='b')

        print(max_value)
        # 绘制刻度线 先确定刻度线最大值外围情况
        for i in range(0, 10000, 200):
            if max_value < i:
                max_value = i
                break

        print(max_value)
        # 再确定一下具体的Step的数值是多少了,之后绘制就可以根据情况来了
        step_value = math.floor(max_value / len(titles))
        print(step_value)
        for j in np.arange(0, max_value, step_value):
            ax.plot(theta, len(theta) * [j], '--', lw=0.5, color='black')
        # 绘制从中心到四周的轴线
        for j in range(len(theta)):
            ax.plot([theta[j], theta[j]], [0, 1000], '--', lw=0.5, color='black')

        # 图形设置
        ax.set_theta_zero_location('N')  # 设置极坐标的起点(即0°)在正北方向,即相当于坐标轴逆时针旋转90°
        ax.set_thetagrids(theta * 180 / np.pi, titles + titles[:1])  # 绘制外层标签
        ax.spines['polar'].set_visible(False)  # 隐藏最外圈的圆
        ax.grid(False)  # 隐藏圆形网格线
        ax.set_theta_zero_location('N')  # 角度专项正北
        ax.set_rlim(0, max_value)  # 设置半径上面的刻度
        ax.set_rlabel_position(0)  # 设置半径标签偏转
        # 添加图例和标题 loc为图例位置
        plt.legend(labels=(self.__ctx__['month_to_do']), loc='lower right', frameon=True, bbox_to_anchor=(1.5, 0.0))
        plt.title("事件分布")
        # plt.savefig(self.__ctx__["module_name"] + "/output/test.png")

        plt.show()
Ejemplo n.º 21
0
def draw_radar():
    angles = np.linspace(0, 2 * np.pi, 6, endpoint=False)
    data = np.concatenate((datas, [datas[0]]))
    angles = np.concatenate((angles, [angles[0]]))
    fig = plt.figure(facecolor="white")
    plt.subplot(111, polar=True)
    plt.plot(angles, data, 'o-', linewidth=1, alpha=0.2)
    plt.fill(angles, data, alpha=0.25)
    plt.thetagrids(angles * 180 / np.pi, radar_labels, fmt=1.2)
    plt.figtext(0.52, 0.95, '霍兰德人格分析', ha='center', size=20)
    legend = plt.legend(data_labels, loc=(0.94, 0.80), labelspacing=0.1)
    plt.setp(legend.get_texts(), fontsize='large')
    plt.grid(True)
    plt.savefig('holland_radar.jpg')
    plt.show()
def polar_axis():
    theta = np.arange(0, 2 * np.pi, 0.02)
    plt.subplot(121, polar=True)
    plt.plot(theta, 1.6 * np.ones_like(theta), lw=2)
    plt.plot(3 * theta, theta / 3, '--', lw=2)

    plt.plot(theta, 1.4 * np.cos(5 * theta), '--', color='green', lw=2)
    plt.plot(theta, 1.8 * np.cos(4 * theta), lw=2)

    # 设置同心圆栅格的大小和文字标准的角度
    plt.rgrids(np.arange(0.5, 2, 0.5), angle=45)

    # 设置放射线栅格的角度
    plt.thetagrids([0, 45])

    plt.show()
Ejemplo n.º 23
0
def pol(df):
    # 绘制不同主演人数分类的烂片占比图示
    plt.figure(figsize=(5,5))
    ax = plt.subplot(111, projection='polar')
    ax.set_title('不同主演人数分类的烂片占比')
    th = np.arange(0, 2*np.pi, 2*np.pi/5)

    ax.bar(th, df['电影数量'], color='burlywood')
    ax.bar(th, df['烂片量'], color='chocolate')
    plt.legend(['电影数量', '烂片量'], loc=(0.83, 0.9))

    for i, j in zip(th, df['烂片占比']):
        plt.text(i, 300, '%.1f%%'%(j*100), color='brown')
    
    plt.thetagrids(np.arange(0, 360, 72), labels=['1-2人','3-4人','5-6人','7-9人','10人以上'])
    plt.savefig('不同主演人数分类的烂片占比.jpg')
Ejemplo n.º 24
0
def plot_phaseplot_lpf(dictdata, keys, autok, title, withn='yes'):
    colors = ['r', 'b', 'g', 'y', 'k']
    
    plt.suptitle(title, fontsize='large' )
    if autok == 'yes':
        k = dictdata.keys()
    
    for i, condition in enumerate(keys):
        datac = colors[i]
        data = dictdata[condition]
        
        try:
            n = len(data)
            theta, r = zip(*data)
        except TypeError:
            theta, r = data
            n = 1
        if withn == 'yes':
            plt.polar(theta, r, 'o', color=datac, label=condition + '\n n=' + str(n))
        if withn == 'no':
            plt.polar(theta, r, 'o', color=datac, label=condition)

        #lines, labels = plt.rgrids( (1.0, 1.4), ('', ''), angle=0 )
        tlines, tlabels = plt.thetagrids( (0, 90, 180, 270), ('0', 'pi/2', 'pi', '3pi/2') )
        leg = plt.legend(loc=(0.95,0.75))
  
        for t in leg.get_texts():
            t.set_fontsize('small')
            
        plt.subplots_adjust(top=0.85)
        plt.draw()
Ejemplo n.º 25
0
def pol2(df):
    # 10部以上的导演的烂片占比图示
    plt.figure(figsize=(5,5))
    ax = plt.subplot(111, projection='polar')
    ax.set_title('导过10部以上电影导演的烂片占比')
    th = np.arange(0, 2*np.pi, 2*np.pi/5)

    ax.bar(th, df['moviesum'], color='burlywood')
    ax.bar(th, df['badmovie'], color='chocolate')
    plt.legend(['电影数量', '烂片量'], loc=(0.83, 0.9))

    for i, j in zip(th, df['bad_per']):
        plt.text(i, 10, '%.1f%%'%(j*100), color='brown')
    
    plt.thetagrids(np.arange(0, 360, 72), labels=['王晶','周伟','邓衍成','海涛','胡明凯'])
    plt.savefig('10部以上电影导演的烂片占比.jpg')
Ejemplo n.º 26
0
 def plotSpeedBear(self, sAllData, bAllData):
     """
     Plot speed and bearing against each other
     """
     plt.figure(self.figurenum(), figsize=(7, 7))
     plt.subplot(111)
     ii = np.where((sAllData < sys.maxsize) & (bAllData < sys.maxsize))
     plt.polar((np.pi / 2. - np.radians(bAllData[ii])),
               sAllData[ii],
               'k.',
               markersize=2)
     thetalabels = (90 - np.arange(0, 360, 45))
     ii = np.where(thetalabels < 0)
     thetalabels[ii] += 360
     lines, labels = plt.rgrids(np.arange(20., 101., 20.),
                                labels=None,
                                angle=67.5)
     lines, labels = plt.thetagrids(np.arange(0., 360., 45.), thetalabels)
     plt.ylim(0, 100.)
     plt.grid(True)
     r = np.corrcoef(bAllData[ii], sAllData[ii])[1, 0]
     plt.text(45,
              125,
              "r = %5.3f" % r,
              ha='center',
              va='center',
              color='r',
              size=14)
     plt.title("Speed vs bearing")
     self.savefig('spd_bear_corr')
Ejemplo n.º 27
0
    def _open_figure(self):
        # Create axis
        self.fig = plt.figure(figsize=(12, 9))
        self.ax = self.fig.add_subplot(111, polar=True)

        # Set up ticks and labels
        self.r_ticks = range(self.r0, self.r0 + (self.nrange + 1) * self.dr,
                             self.dr)
        self.theta_ticks = [
            self.theta0 + self.dtheta * b for b in range(self.nbeam + 1)
        ]
        rlabels = [""] * len(self.r_ticks)
        for i in range(0, len(rlabels), 5):
            rlabels[i] = i
        plt.rgrids(self.r_ticks, rlabels)
        plt.thetagrids(self.theta_ticks, range(self.nbeam))
Ejemplo n.º 28
0
    def create_chart(self):
        for i in reversed(range(self.layout.count())):
            self.layout.itemAt(i).widget().deleteLater()
        params = ['TRL', 'MRL', 'ERL', 'ORL', 'CRL']
        results = []
        for el in params:
            results.append(float(self.data[el]))

        results = np.append(results, results[0])
        self.figure = plt.figure(figsize=(12, 12), facecolor='#f3f3f3')
        plt.subplot(polar=True)
        theta = np.linspace(start=0, stop=2 * np.pi, num=len(results))
        ax = self.figure.add_subplot(111, projection='polar')
        ax.set(facecolor='#f3f3f3')
        ax.set_theta_offset(np.pi / 2)
        ax.set_theta_direction(-1)
        ax.set_ylim(0, 9)
        ax.set_yticks(np.arange(0, 10, 1.0))
        plt.yticks([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], fontsize=6, color='grey')
        ax.set_rlabel_position(0)
        gridlines = ax.yaxis.get_gridlines()
        for gl in gridlines:
            gl.get_path()._interpolation_steps = 5
        plt.box(on=None)
        lines, labels = plt.thetagrids(range(0, 360, int(360 / len(params))),
                                       (params))
        plt.plot(theta, results)
        plt.fill(theta, results, 'b', alpha=0.1)
        plotWidget = FigureCanvas(self.figure)
        self.layout.addWidget(plotWidget, Qt.AlignVCenter)
def draw(folders):
    """ Draw folder size for given folder"""
    figsize = (8, 8)  # keep the figure square
    ldo, rup = 0.1, 0.8  # left down, right up coordinates, normalized
    fig = plt.figure(figsize=figsize)
    ax = fig.add_axes([ldo, ldo, rup, rup], polar=True)

    # transform data
    x = [os.path.basename(x['path']) for x in folders]
    y = [y['size'] / 1024 / 1024 for y in folders]
    theta = np.arange(0.0, 2 * np.pi, 2 * np.pi / len(x))
    radii = y

    bars = ax.bar(theta, radii)
    middle = 90 / len(x)
    theta_ticks = [t * (180 / np.pi) + middle for t in theta]
    lines, labels = plt.thetagrids(theta_ticks, labels=x, frac=0.5)
    for step, each in enumerate(labels):
        each.set_rotation(theta[step] * (180 / np.pi) + middle)
        each.set_fontsize(8)

    # configure bars
    colormap = lambda r: cm.Set2(r / len(x))
    for r, each in zip(radii, bars):
        each.set_facecolor(colormap(r))
        each.set_alpha(0.5)

    plt.show()
Ejemplo n.º 30
0
def visualization(categories,
                  all_scores,
                  candidate_names=['KANDIDAT 1', 'KANDIDAT 2'],
                  show=False):

    label_loc = np.linspace(start=0, stop=2 * np.pi, num=len(categories))

    plt.figure(figsize=(8, 8))
    plt.subplot(polar=True)

    for candidate in candidate_names:
        for name_score in all_scores:
            if candidate == name_score['name']:
                the_scores = name_score['scores']
                the_scores = [*the_scores, the_scores[0]]
                plt.plot(label_loc, the_scores, label=candidate)

    plt.title('Candidates comparison', size=20, y=1.05)
    lines, labels = plt.thetagrids(np.degrees(label_loc), labels=categories)
    plt.legend()

    cwd = os.getcwd()
    filename = f'candidates_comparasion-{str(time.ctime()).replace(" ", "_")}.png'
    file_to_save = os.path.join(cwd, filename)
    print(f'File to save: {file_to_save}')
    plt.savefig(file_to_save)

    if show:
        plt.show()

    return os.path.join(os.getcwd(), filename)
Ejemplo n.º 31
0
def draw(folders):
    """ draw folder size for given folder"""
    figsize = (8, 8)    # keep the figure square
    ldo, rup = 0.1, 0.8     # leftdown and right up normalized
    fig = plt.figure(figsize=figsize)
    ax = fig.add_axes([ldo, ldo, rup, rup], polar=True)

    # transform data
    x = [os.path.basename(x['path']) for x in folders]
    y = [y['size'] / 1024 / 1024 for y in folders]
    theta = np.arange(0, 2 * np.pi, 2 * np.pi / len(x))
    radii = y

    bars = ax.bar(theta, radii)
    middle = 90 / len(x)
    theta_ticks = [t * (180 / np.pi) + middle for t in theta]
    lines, labels =plt.thetagrids(theta_ticks, labels=x, frac=0.5)
    for step, each in enumerate(labels):
        each.set_rotation(theta[step] * (180 / np.pi) + middle)
        each.set_fontsize(8)

    # configure bars
    colormap = lambda r:cm.Set2(r / len(x))
    for r, each in zip(radii, bars):
        each.set_facecolor(colormap(r))
        each.set_alpha(0.5)

    plt.show
Ejemplo n.º 32
0
def flowers(n):
    a=[4,5,6,7,0.75,2.5,3.5,5.0/3.0,7.0/3.0,7.0/4.0,1.0/6.0,1.0/8.0,1.0/7.0,2.0/9.0]
    if a[n-1]>=4:
        b='yellow'
    elif a[n-1]<=1:
        b='red'
    else:
        b='magenta'
    pyplot.axes(polar=True)
    pyplot.thetagrids([])
    pyplot.rgrids([2])
    theta = arange(-9, 9, 1./180)*pi # angular coordinates
    figure(1)
    pyplot.plot(theta, cos(a[n-1]*theta), color=b, linewidth=5) # drawing the polar rose
    show()
    return
Ejemplo n.º 33
0
def drawradar(c):
    labels = np.array(['aa', 'bb', 'cc', 'dd', 'ee', 'ff'])
    # data = np.array([1, 4, 3, 6, 4, 8])
    data = c
    angles = np.linspace(0, 2 * np.pi, data.shape[0], endpoint=False)
    # 闭合
    data = np.hstack([data, data[0]])
    angles = np.hstack([angles, angles[0]])
    plt.polar(angles, data, 'ro-', linewidth=2)
    # 标签
    plt.thetagrids(angles * 180 / np.pi, labels)
    # 填充
    plt.fill(angles, data, facecolor='b', alpha=0.25)
    plt.title('radar')
    plt.ylim(0, 10)
    plt.grid(True)
    plt.show()
Ejemplo n.º 34
0
def draw_radar():
    '''根据多支股票绘制 最高、最低、今开、昨收、涨停、跌停 雷达图
    有实际意义,可对两支股票作对比
    '''
    df = read_excel()  # 读取数据
    print(df)
    print("请根据以上展示信息,输入两支股票索引进行对比!")
    print("例如:输入1,然后回车; 再输入2,然后回车; 即可对第2、3支股票进行对比。")
    num1 = int(input(">>>>>>>>>>【输入待展示的股票序号1】<<<<<<<<<\n"))
    num2 = int(input(">>>>>>>>>>【输入待展示的股票序号2】<<<<<<<<<\n"))
    # 选取 最高、最低、今开、昨收、涨停、跌停 这五列标题
    titles = df.columns.tolist()[2:8]
    # 股票一
    stock_name1 = df["股票名称"][num1]
    stock_code1 = df["股票代码"][num1]
    data1 = df.loc[num1].tolist()[2:8]  # 选取 最高、最低、今开、昨收、涨停、跌停 这六列数据
    # 股票二
    stock_name2 = df["股票名称"][num2]
    stock_code2 = df["股票代码"][num2]
    data2 = df.loc[num2].tolist()[2:8]  # 选取 最高、最低、今开、昨收、涨停、跌停 这六列数据
    data = [data1, data2]
    N = len(titles)  # 雷达图等分数目
    titles.append(titles[0])  # 标题数目和数据一致

    # 样式 大于当前的5
    sam = ['r-', 'm-', 'g-', 'b-', 'y-', 'k-', 'w-', 'c-']
    for i in range(len(data)):
        values = data[i]
        # 设置雷达图的角度,平分圆面
        angles = np.linspace(0, 2 * np.pi, N, endpoint=False)
        # 雷达图封闭 两种方法
        # values.append(values[0])
        values = np.concatenate((values, [values[0]]))
        # 角度
        angles = np.append(angles, angles[0])
        # 绘制折线图
        plt.polar(angles, values, sam[num1 % 5], lw=2)
        # 添加特征标签
        plt.thetagrids(angles * 180 / np.pi, titles)
        # 填充颜色
        plt.fill(angles, values, facecolor='c', alpha=0.4)
        # 标题
        plt.title('【' + stock_name1 + stock_code1 + '】 VS 【' + stock_name2 +
                  stock_code2 + '】')
    plt.show()
Ejemplo n.º 35
0
def roseDiagram(data, nbins=30, bidirectional=True, title='North'):
    """Plots a circular histogram or "rose diagram"
    Input: 
        data: A list or 1D array of orientation data that the histogram 
            will be made from. The data should be an in degrees clockwise
            from north.
        nbins (default: 30): The number of bins in the histogram
        bidirectional (default: True): Whether or not to treat the input data
            as bi-directional. (i.e. if True, the rose diagram will be 
            symmetric)
        title (default: 'North'): The title of the plot
    """
    # TODO: This needs to pass kwargs on to the plotting routines
    # TODO: (or just remove this function entirely? It shouldn't 
    # TODO: really be here)
    from matplotlib import pyplot as plt
    data = np.asarray(data)
    n = data.size

    if bidirectional:
        # Rather than doing some sort of fancy binning, just
        #  "double" the data with the complimentary end (+180)
        data = np.append(data, data+180)
        data[data>360] -= 360

    # Rotate the data so that north will plot at the top 
    # (90deg, in polar space)
    data = 90-data
    data[data<0] += 360

    # Make a figure with polar axes
    fig = plt.figure()
    ax = fig.add_axes([0.1, 0.1, 0.8, 0.7], polar=True, axisbg='#d5de9c')

    # Change the labeling so that north is at the top
    plt.thetagrids(range(0,360,45), 
            ['90','45','0','315','270','225','180','135'])

    # Plot a histogram on the polar axes
    data = np.radians(data)
    plt.hist(data, bins=nbins, axes=ax)
    plt.title(title + '\nn=%i'%n)
Ejemplo n.º 36
0
def schmidt(name="strike.xlsx", Width=1, Color='k'):


    if("csv"in name):schmidtraw  = pd.read_csv(name)
    elif("xlsx"in name):schmidtraw  = pd.read_excel(name)


    Data = []

    plt.axes(polar=True)
    plt.polar([0], [90])
    plt.xlim((0, 360))
    plt.ylim((0, 90))

    list1 = [eqar(x) for x in range(0, 90, 15)]
    list2 = [str(x) for x in range(0, 90, 15)]
    plt.rgrids(list1, list2)

    for i in range(len(schmidtraw)):
        Data.append(
            [schmidtraw.at[i, "Name"], schmidtraw.at[i, "Strike"], schmidtraw.at[i, "Dip"], schmidtraw.at[i, "Color"],
             schmidtraw.at[i, "Width"], schmidtraw.at[i, "Alpha"], schmidtraw.at[i, "Marker"]])
        S = schmidtraw.at[i, "Strike"]
        D = schmidtraw.at[i, "Dip"]
        Width = schmidtraw.at[i, "Width"]
        Color = schmidtraw.at[i, "Color"]
        Alpha = schmidtraw.at[i, "Alpha"]
        Marker = schmidtraw.at[i, "Marker"]

        plt.plot(np.radians(90 - S), eqar(D), color=Color, linewidth=Width, alpha=Alpha, marker=Marker)

    plt.plot(120, 30, color='K', linewidth=4, alpha=Alpha, marker='o')
    plt.thetagrids(range(360 + 90, 0 + 90, -20), [str(x) for x in range(0, 360, 20)])
    plt.savefig("Schmidt.png", dpi=600)
    plt.savefig("Schmidt.svg", dpi=600)
    plt.show()
Ejemplo n.º 37
0
def wulf(name="strike.xlsx", Width=1, Color='k'):


    if("csv"in name):wulfraw  = pd.read_csv(name)
    elif("xlsx"in name):wulfraw = pd.read_excel(name)


    Data = []

    plt.axes(polar=True)
    plt.polar([0], [90])
    plt.xlim((0, 360))
    plt.ylim((0, 90))

    list1 = [eqan(x) for x in range(0, 90, 15)]
    list2 = [str(x) for x in range(0, 90, 15)]
    plt.rgrids(list1, list2)

    for i in range(len(wulfraw)):
        Data.append([wulfraw.at[i, "Name"], wulfraw.at[i, "Strike"], wulfraw.at[i, "Dip"], wulfraw.at[i, "Color"],
                     wulfraw.at[i, "Width"], wulfraw.at[i, "Alpha"]])
        S = wulfraw.at[i, "Strike"]
        D = wulfraw.at[i, "Dip"]
        Width = wulfraw.at[i, "Width"]
        Color = wulfraw.at[i, "Color"]
        Alpha = wulfraw.at[i, "Alpha"]
        r = np.arange(S - 90, S + 91, 1)
        BearR = [np.radians(-A + 90) for A in r]
        Line = (eqan(getangular(D, S, r)))

        plt.plot(BearR, Line, color=Color, linewidth=Width, alpha=Alpha)

    plt.thetagrids(range(360 + 90, 0 + 90, -20), [str(x) for x in range(0, 360, 20)])
    plt.savefig("Wulff.png", dpi=600)
    plt.savefig("Wulff.svg", dpi=600)
    plt.show()
Ejemplo n.º 38
0
def plot_phaseplot(dictdata, keys, autok, title, withn='yes'):
    """Plots a phase plot where the radius is fixed at 1"""
    
    colors = ['r', 'b', 'g', 'y', 'k']

    if autok == 'yes':
        k = dictdata.keys()
        
    plt.suptitle(title, fontsize='large' )
    
    for i, condition in enumerate(keys):
    #for i, condition in enumerate(iter(dictdata)):
        data = dictdata[condition]
        datac = colors[i]
        try:
            n = len(data)
            theta = []
            theta.extend(data)
            r1 = 1
            r = np.repeat(r1, n)
        
        except TypeError:
            r = 1
            theta = data
            n = 1
            
        if withn == 'yes':
            plt.polar(theta, r, 'o', color=datac, label=condition + '\n n=' + str(n))
        if withn == 'no':
            plt.polar(theta, r, 'o', color=datac, label=condition)
        
        lines, labels = plt.rgrids( (0.5, 1.0), ('', ''), angle=0 )
        tlines, tlabels = plt.thetagrids( (0, 90, 180, 270), ('0', 'pi/2', 'pi', '3pi/2') )
        leg = plt.legend(loc='center')
        for t in leg.get_texts():
            t.set_fontsize('small')
            
        plt.subplots_adjust(top=0.85)
        plt.draw()        
Ejemplo n.º 39
0
 def plotSpeedBear(self, sAllData, bAllData):
     """
     Plot speed and bearing against each other
     """
     pyplot.figure(self.figurenum(), figsize=(7, 7))
     pyplot.subplot(111)
     ii = numpy.where((sAllData < sys.maxint) & (bAllData < sys.maxint))
     pyplot.polar((numpy.pi/2. - numpy.radians(bAllData[ii])), sAllData[ii],
                  'k.', markersize=2)
     thetalabels=(90 - numpy.arange(0, 360, 45))
     ii = numpy.where(thetalabels < 0)
     thetalabels[ii] += 360
     lines, labels = pyplot.rgrids(numpy.arange(20., 101., 20.),
                                   labels=None, angle=67.5)
     lines, labels = pyplot.thetagrids(numpy.arange(0., 360., 45.),
                                       thetalabels)
     pyplot.ylim(0, 100.)
     pyplot.grid(True)
     r = numpy.corrcoef(bAllData[ii], sAllData[ii])[1, 0]
     pyplot.text(45, 125, "r = %5.3f"%r, ha='center',
                 va='center', color='r', size=14)
     pyplot.title("Speed vs bearing")
     self.savefig('spd_bear_corr')
Ejemplo n.º 40
0
Archivo: rtd.py Proyecto: adlyons/AWOT
def polar_sweep(
    Var,
    rot,
    range,
    nlevs=30,
    vmin=None,
    vmax=None,
    cmap=None,
    mask_outside=True,
    rng_rings=None,
    rot_angs=None,
    title=None,
    cb_flag=True,
    cb_orient="horizontal",
    cb_lab=None,
):
    """
    Plot a sweep of native (polar) coordinate radar data on polar format plot

    Parameters
    ----------
    Var : float array
        Data values to plot.
    range : float array
        Range along ray.
    rot : float array
        Rotation angle with respect to instrument [degrees].

    THESE NEXT VALUES CUSTOMIZE THE PLOT
    nlevs : int
        Number of contour levels to plot.
    vmin : float
        Minimum value to display.
    vmax : float
        Maximum value to display.
    cmap : str
        Matplotlib colormap name.
    mask_outside : bool
        True to mask values outside vmin/vmax.
    title : str
        Title to label plot with, if none given it is omitted.
    cb_flag : bool
        True turns on colorbar, False no colorbar.
    cb_lab : str
        Colorbar label, None will use a default label generated from the
        field information.
    cb_orient : str
        Orientation of colorbar (vertical or horizontal).

    Output
    ------
    fig : Figure to create plot to
    ax : Polar axis created
    p : Output plot
    """
    # Plot the polar coordinate radar data
    fig, ax, p = gp.plot_polar_contour(Var, rot, range, nlevs=nlevs, vmin=vmin, vmax=vmax, cmap=cmap, mask_outside=True)

    # Set the range and turn grid on
    ax.set_rmax(1.05 * range.max())
    ax.grid(True)

    # Set the title
    if title is None:
        pass
    else:
        ax.set_title(title)

    # Set the range rings if set
    if rng_rings is None:
        pass
    else:
        plt.rgrids(rng_rings)

    # Set the rotation angles (theta) if set
    if rot_angs is None:
        pass
    else:
        plt.thetagrids(rot_angs)

    # Set the colorbar if desired
    if cb_flag:
        cb = plt.colorbar(mappable=p, orientation=cb_orient)
        if cb_lab is None:
            pass
        else:
            cb.set_label(cb_lab)

    return fig, ax, p
#!/usr/bin/python

import matplotlib.pyplot as plt
import numpy as np
theta = np.arange(0., 2., 1./180.)*np.pi
r = np.abs(np.sin(5*theta)-2.*np.cos(theta))
plt.polar(theta, r)
plt.thetagrids(range(45, 360, 90))
plt.rgrids(np.arange(0.2, 3.1, .7), angle=0)
plt.show()
Ejemplo n.º 42
0
"""
#霍兰德人格分析雷达图

import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family']='SimHei'
radar_labels=np.array(['研究型','艺术型','社会型',\
                       '企业型','常规型','现实型'])
data=np.array([[0.40,0.32,0.35,0.3,0.3,0.88],
              [0.85,0.35,0.3,0.4,0.4,0.3],
              [0.43,0.89,0.30,0.28,0.22,0.30],
              [0.3,0.25,0.48,0.85,0.45,0.40],
              [0.2,0.3,0.4,0.53,0.65,0.25],
              [0.34,0.31,0.38,0.40,0.92,0.28]])
data_labels=('艺术家','实验员','工程师','推销员','社会工作者'\
             ,'记事员')
angles=np.linspace(0,2*np.pi,6,endpoint=False)
data=np.concatenate((data,[data[0]]))
angles=np.concatenate((angles,[angles[0]]))
fig=plt.figure(facecolor='white')
plt.subplot(111,polar=True)
plt.plot(angles,data,'o-',linewidth=1,alpha=0.2)
plt.fill(angles,data,alpha=0.25)
plt.thetagrids(angles*180/np.pi,radar_labels,frac=1.2)
plt.figtext(0.52,0.95,'霍兰德人格分析',ha='center',size=20)
legend=plt.legend(data_labels,loc=(0.94,0.80),labelspacing=0.1)
plt.setp(legend.get_texts(),fontsize='large')
plt.grid(True)
plt.savefig('holland_radar.jpg')
plt.show()
Ejemplo n.º 43
0
    def polar(self, plotnum, theta, r, ptitle=None, \
                    plotCol=[], label=[],labelLocation=[-0.1, 0.1], \
                    highlightNegative=False, highlightCol='#ffff00', highlightWidth=4,\
                    legendAlpha=0.0, \
                    rscale=None, rgrid=None, thetagrid=[30], \
                    direction='counterclockwise', zerooffset=0, titlefsize=12):
        """Create a subplot and plot the data in polar coordinates (linear radial orginates only).

        Given an existing figure, this function plots in a specified subplot position.
        The function arguments are described below in some detail. Note that the radial values
        or ordinates can be more than one column, each column representing a different
        line in the plot. This is convenient if large arrays of data must be plotted. If more
        than one column is present, the label argument can contain the legend labels for
        each of the columns/lines.  The scale for the radial ordinates can be set with rscale.
        The number of radial grid circles can be set with rgrid - this provides a somewhat
        better control over the built-in radial grid in matplotlib. thetagrids defines the angular
        grid interval.  The angular rotation direction can be set to be clockwise or
        counterclockwise. Likewise the rotation offset where the plot zero angle must be,
        is set with zerooffset.

            Args:
                | plotnum (int): subplot number
                | theta (np.array[N,] or [N,1]): angular abscissa
                | r (np.array[N,] or [N,M]): radial ordinates - could be M columns
                | ptitle (string): plot title (optional)
                | plotCol ([strings]): plot line style, list with M entries, use default if [] (optional)
                | label  ([strings]): legend label, list with M entries (optional)
                | labelLocation ([x,y]): where the legend should located (optional)
                | highlightNegative (bool): indicate if negative data be highlighted (optional)
                | highlightCol (string): highlighted colour string (optional)
                | highlightWidth (int): highlighted line width(optional)
                | legendAlpha (float): transparancy for legend (optional)
                | rscale ([rmin, rmax]): plotting limits. default if all 0 (optional)
                | rgrid ([rinc, rmax]): radial grid default if all 0. if rinc=0 then rmax is number of ntervals. (optional)
                | thetagrids (float): theta grid interval [degrees] (optional)
                | direction (string)= 'counterclockwise' or 'clockwise' (optional)
                | zerooffset (float) = rotation offset where zero should be [rad] (optional)
                | titlefsize (int): title font size, default 12pt (optional)

            Returns:
                | Nothing

            Raises:
                | No exception is raised.
        """

        if theta.ndim>1:
            tt=theta
        else:
            tt=theta.reshape(-1, 1)

        if r.ndim>1:
            rr=r
        else:
            rr=r.reshape(-1, 1)

        plotCol = self.buildPlotCol(plotCol, rr.shape[1])

        ax = None
        pkey = (self.nrow, self.ncol, plotnum)
        if pkey not in self.subplots.keys():
            self.subplots[pkey] = \
                         self.fig.add_subplot(self.nrow,self.ncol, plotnum, polar=True)

        ax = self.subplots[pkey]

        ax.grid(True)

        rmax=0

        for i in range(rr.shape[1]):
            # negative val :forcing positive and phase shifting
            # if forceAbsolute:
            #     ttt = tt + numpy.pi*(rr[:, i] < 0).reshape(-1, 1)
            #     rrr = numpy.abs(rr[:, i])
            # else:
            ttt = tt
            rrr = rr[:, i]

            #print(rrr)

            if highlightNegative:
                #find zero crossings in data
                zero_crossings = numpy.where(numpy.diff(numpy.sign(rr),axis=0))[0]
                #split the input into different subarrays according to crossings
                negrrr = numpy.split(rr,zero_crossings)
                negttt = numpy.split(tt,zero_crossings)
                #print(zero_crossings)
                #print(negrrr)

            if not label:
                if highlightNegative:
                    lines = ax.plot(ttt, rrr, plotCol[i])
                    neglinewith = highlightWidth*plt.getp(lines[0],'linewidth')
                    for ii in range(0,len(negrrr)):
                        if len(negrrr[ii]) > 0:
                            if negrrr[ii][1] < 0:
                                ax.plot(negttt[ii], negrrr[ii], highlightCol,linewidth=neglinewith)
                ax.plot(ttt, rrr, plotCol[i])
                rmax=numpy.maximum(numpy.abs(rrr).max(), rmax)
            else:
                if highlightNegative:
                    lines = ax.plot(ttt, rrr, plotCol[i])
                    neglinewith = highlightWidth*plt.getp(lines[0],'linewidth')
                    for ii in range(0,len(negrrr)):
                        if len(negrrr[ii]) > 0:
                            if negrrr[ii][1] < 0:
                                ax.plot(negttt[ii], negrrr[ii], highlightCol,linewidth=neglinewith)
                ax.plot(ttt, rrr, plotCol[i],label=label[i])
                rmax=numpy.maximum(numpy.abs(rrr).max(), rmax)

        if label:
            fontP = mpl.font_manager.FontProperties()
            fontP.set_size('small')
            leg = ax.legend(loc='upper left',
                    bbox_to_anchor=(labelLocation[0], labelLocation[1]),
                    prop = fontP, fancybox=True)
            leg.get_frame().set_alpha(legendAlpha)
            self.bbox_extra_artists.append(leg)


        ax.set_theta_direction(direction)
        ax.set_theta_offset(zerooffset)


        #set up the grids
        plt.thetagrids(range(0, 360, thetagrid[0]))

        if rgrid is None:
            ax.set_yticks(numpy.linspace(0,rmax,5))
        else:
            if rgrid[0]==0:
                if rmax>0:
                    #round and increase the max value for nice numbers
                    lrmax=round(math.floor(math.log10(rmax/rgrid[1])))
                    frmax=rmax/(rgrid[1]*10**lrmax)
                    rinc=10**lrmax*math.ceil(frmax)
                    plt.rgrids(numpy.arange(rinc, rinc*rgrid[1], rinc))
            else:
                plt.rgrids(numpy.arange(rgrid[0], rgrid[1], rgrid[0]))



        #Set increment and maximum radial limits
        if rscale is not None:
            ax.set_ylim(rscale[0],rscale[1])
            ax.set_yticks(numpy.linspace(rscale[0],rscale[1],5))
        else:
            ax.set_ylim(0,rmax)


        if(ptitle is not None):
            ax.set_title(ptitle, fontsize=titlefsize, \
                verticalalignment ='bottom', horizontalalignment='center')
Ejemplo n.º 44
0
plt.gca().xaxis.set_major_formatter(mpl.ticker.FuncFormatter(lambda x, _: int(x * 1e-3)))
plt.legend(loc='lower right')
plt.tight_layout()
plt.savefig('loesung-log.pdf')

plt.clf()

x = np.linspace(2 * np.pi * 27e1, 2 * np.pi * 50e4, 1000)
phi1 = np.arctan(1 / R * (L * x - 1 / (C * x)))
phi2 = -phi1
Z_theor = np.sqrt(R**2 + (L * x - 1 / (C * x))**2)

plt.polar(phi1, Z_theor,'b', label='Theoriekurve')
plt.polar(phi2, Z_theor, 'b')
plt.polar(arg, Z, 'rx', label='Messwerte')
plt.ylim(0, 600)
plt.xlabel(r'$\varphi \,/\, \mathrm{rad}$')
plt.figtext(0.67, 0.68, r'$|Z| \,/\, \mathrm{\Omega}$')
plt.thetagrids([0, 45, 90, 135, 180, 225, 270, 315], labels=[r'$0$',
                                                             r'$\frac{1}{4} \pi$',
                                                             r'$\frac{1}{2} \pi$',
                                                             r'$\frac{3}{4} \pi$',
                                                             r'$\pm \pi$',
                                                             r'$- \frac{3}{4} \pi$',
                                                             r'$- \frac{1}{2} \pi$',
                                                             r'$- \frac{1}{4} \pi$'])
plt.rgrids([200, 400, 600])
plt.legend(bbox_to_anchor=(0.45, 0.8, 0, 0))
plt.tight_layout()
plt.savefig('loesung-polar.pdf')
for index, course in enumerate(new_course_list):
	for index2, course2 in enumerate(pm_req):
		if course == course2:
			colors[index] = 'yellow'
	final_label_course.append('')

for index, course in enumerate(pm_req):
	for index2, course2 in enumerate(new_course_list):
		if course == course2:
			final_label_course[index2] = course


ax = subplot(111, polar=True)
ax.set_ylim(0,1)
ax.set_rlabel_position(0)
plt.thetagrids(range(0))

theta.append(0)
area.append(100)
colors.append('black')
r.append(0)

count = 0 
for axis in zip(theta,r): 
	ax.annotate(new_course_list[count], xy = axis, xytext = (-2, 2),
        textcoords = 'offset points', ha = 'right', va = 'bottom',
        bbox = dict(boxstyle = 'round,pad=0.3', fc = 'white', alpha = 0.01))
	count += 1


for i in range(len(area)):
Ejemplo n.º 46
0
import numpy as np
import math
from matplotlib import rc

rc('font',**{'family':'serif','serif':['Times']})
## for Palatino and other serif fonts use:
#rc('font',**{'family':'serif','serif':['Palatino']})
rc('text', usetex=True)

plt.rcParams["legend.fontsize"] = "small"
plt.rcParams['figure.figsize'] = 5, 5
#plt.rcParams['figure.dpi'] = 300

data = sio.loadmat('velocity_polar.mat')
position = data['position']
velocity = data['velocity']


plt.polar(position,velocity,'r.--',label="Estimated velocity",linewidth=1.5)
plt.rgrids(velocity,'velocity (rpm)')
plt.thetagrids(position,'position (rad)')
plt.xlim (0,1.2)
plt.ylim (0,20)
plt.legend()
plt.tight_layout()

plt.savefig("velocity_posture.eps",bbox_inches='tight',dpi=600)
plt.savefig("velocity_posture.pdf",bbox_inches='tight',dpi=600)
plt.savefig("velocity_posture.tif",bbox_inches='tight',dpi=600)

plt.show()
Ejemplo n.º 47
0
    def plot_polar_sweep(self, field, nlevs=30, mask_procedure=None,
                         mask_tuple=None,
                         vmin=None, vmax=None, cmap='gist_ncar',
                         rng_rings=None, rot_angs=None,
                         cb_flag=True, cb_orient=None, cb_label=None,
                         title=None, ax=None, fig=None):
        """
        Plot a sweep of native (polar) coordinate radar data
        on polar format plot

        Parameters
        ----------
        field : str
            Variable name (e.g. 'reflectivity') to use in plot.
        nlevs : int
            Number of contour levels to plot.
        mask_procedure : str
            String indicating how to apply mask via numpy, possibilities are:
            'less', 'less_equal', 'greater', 'greater_equal',
            'equal', 'inside', 'outside'.
        mask_tuple : (str, float[, float])
            Tuple containing the field name and value(s) below which to mask
            field prior to plotting, for example to mask all data where.
        vmin : float
            Minimum value to display.
        vmax : float
            Maximum value to display.
        cmap : str
            Matplotlib color map to use.
        cb_flag : bool
            True turns on colorbar, False no colorbar.
        cb_orient : str
            Orientation of colorbar ('vertical' or 'horizontal').
        cb_label : str
            Colorbar label, None will use a default label generated from the
            field information.
        title : str
            Title to label plot with, if none given it is omitted.
        ax : Matplotlib axis instance
            Axis to plot. None will use the current axis.
        fig : Matplotlib figure instance
            Figure on which to add the plot. None will use the current figure.

        Notes
        -----
        Variables used to calculate polar coordinate positions:
        Rotation angle with respect to instrument [degrees].
        Range along ray [m].

        Defaults are established during DYNAMO project analysis
        """
        # parse parameters
        ax, fig = _parse_ax_fig(ax, fig)

        # Get variable
        Var, Data = _get_variable_dict_data(self.fields, field)

        if mask_procedure is not None:
            Data = get_masked_data(Data, mask_procedure, mask_tuple)

        if vmin is None:
            vmin = Data.min()

        if vmax is None:
            vmax = Data.max()

        # Set variable for calculation
        range, rotation = self._get_2D_var(self.rotation['data'][:])

        # Plot the polar coordinate radar data
        p = plot_polar_contour(Data, rotation, range,
                               nlevs=nlevs, vmin=vmin, vmax=vmax, cmap=cmap)

        # Set the range and turn grid on
        ax.set_rmax(1.05 * range.max())
        ax.grid(True)

        # Set the title
        if title is None:
            pass
        else:
            ax.set_title(title)

        # Set the range rings if set
        if rng_rings is None:
            pass
        else:
            plt.rgrids(rng_rings)

        # Set the rotation angles (theta) if set
        if rot_angs is None:
            pass
        else:
            plt.thetagrids(rot_angs)

        # Set the colorbar if desired
        if cb_flag:
            cb = plt.colorbar(mappable=p, orientation=cb_orient)
            if cb_label is None:
                cb_label = Var['long_name'] + ' (' + Var['units'] + ')'
            else:
                cb.set_label(cb_label)

        return
Ejemplo n.º 48
0
    def singlerose(self, Gap=10,Width=1,Name=['Dip'], Color=['red']):
        """
        draw the rose map of single sample with different items~
        """
        plt.figure(figsize=(self.Width, self.Height), dpi=self.Dpi)
        plt.axes(polar=True)
        plt.polar([0], [90])
        plt.xlim((0, 360))
        plt.ylim((0, 90))
        
        real_max=[]

        for k in range(len(Name)):
            
            
                
            Data = []
            S=[]
            R=[]
            for i in range(len(self.raw)):
                S.append(self.raw.at[i, Name[k]])
    
            
            s= np.linspace(0,360,360/Gap+1)
            t= tuple(s.tolist())
            count=[]
            
            for i in range(len(t)):
                tmp_count=0
                for j in S:
                    if i < len(t)-1:
                        if t[i]<j<=t[i+1]:
                            tmp_count+=1
                count.append(tmp_count)
                
            count_max =max(count)
            real_max.append(count_max)
            
            

            
        maxuse=max(real_max)   
        
        
        
        for k in range(len(Name)):   
            Data = []
            S=[]
            R=[]
            for i in range(len(self.raw)):
                S.append(self.raw.at[i, Name[k]])
    
            
            s= np.linspace(0,360,360/Gap+1)
            t= tuple(s.tolist())
            count=[]
            
            for i in range(len(t)):
                tmp_count=0
                for j in S:
                    if i < len(t)-1:
                        if t[i]<j<=t[i+1]:
                            tmp_count+=1
                count.append(tmp_count)
            s= np.linspace(0,360,360/Gap+1)
            t= tuple(s.tolist())
            
            R_factor = 90/maxuse
            
            for i in count:
                TMP=90- i *R_factor
                R.append(TMP)
                        
            m,n=Polar().Trans(t,R)
            plt.plot(m,n, color=Color[k], linewidth=1, alpha=0.6, marker='')
            plt.fill(m, n, Color=Color[k], Alpha=0.6, )
            
        list1 = [self.eqar(x) for x in range(0, 90, 15)]
        list2 = [str(x) for x in range(0, int(maxuse+1), int((maxuse+1)/7))]
        list2.reverse()
        plt.rgrids(list1, list2)
            
        
        plt.thetagrids(range(360 + 90, 0 + 90, -15), [str(x) for x in range(0, 360, 15)])

        plt.legend(loc=5, bbox_to_anchor=(1.5, 0.5))

        plt.savefig(self.name + "Rose.png", dpi=300)
        plt.savefig(self.name + "Rose.svg", dpi=300)
        plt.show()
Ejemplo n.º 49
0
for k in range(0,12):
    for j in range(1,7):
        for i in range(0,271):
            data[k][j].append(data[k][j][271-i])



"""L = 4.6 """

""" ECH """
plt.figure(1)

data[0][0] = [math.radians(a) for a in data[0][0]]
ax = plt.subplot(2,3,1, polar = True)
ax.set_theta_zero_location("N")
plt.thetagrids([0,15,30,45,60,75,90,105,120,135,150,165,180,195,210,225,240,255,270,285,300,315,330,345])
ax.set_theta_direction(-1)
plt.plot(data[0][0],data[0][1], 'k', label = 'ECH')
plt.plot(data[0][0],data[1][1], 'r', label = 'No Waves')
plt.legend(loc='center left', fontsize='small')
plt.figtext(0.1,.78,'E = 2 eV', fontsize = 18, fontweight = 'bold', rotation = 'vertical')
plt.figtext(0.1,.33,'E = 20 eV', fontsize = 18, fontweight = 'bold', rotation = 'vertical')
plt.figtext(0.38,.78,'E = 5 eV', fontsize = 18, fontweight = 'bold', rotation = 'vertical')
plt.figtext(0.38,.33,'E = 30 eV', fontsize = 18, fontweight = 'bold', rotation = 'vertical')
plt.figtext(0.66,.78,'E = 10 eV', fontsize = 18, fontweight = 'bold', rotation = 'vertical')
plt.figtext(0.66,.33,'E = 50 eV', fontsize = 18, fontweight = 'bold', rotation = 'vertical')
plt.suptitle('Normalized Pitch Angle Distribution at the Equator for ECH at L = 4.6 ', fontsize = 18, fontweight = 'bold')
plt.yscale('log')
plt.ylim(1,1000)

ax = plt.subplot(2,3,2, polar = True)
Ejemplo n.º 50
0
def spider_plot(figure,Y,color1,color2=None,xlabels=[],ytargets=None,y_std=None,n_points=400,smooth_factor=0.1,filled=True,spline_order=1,linewidth=3,label=""):
    
    if color2 is None:
        color2 = color1

    font = fm.FontProperties(family = 'Trebuchet', weight ='light')
    #font = fm.FontProperties(family = 'CenturyGothic',fname = '/Library/Fonts/Microsoft/Century Gothic', weight ='light')
    figure.patch.set_facecolor('white')
    axes = figure.add_subplot(111,polar=True)

    n_axes = Y.shape[0]

    X = (np.arange(n_axes)*2*np.pi)/n_axes
    X = np.concatenate([X,[2*np.pi]])
    Y = np.concatenate([Y,[Y[...,0]]])

    X_smooth = np.linspace(X.min(),X.max(),n_points)
    tck = splrep(X,Y,s=smooth_factor,k=spline_order)
    Y_smooth = splev(X_smooth,tck,der=0)

    if y_std is not None:
        y_std = np.concatenate([y_std,[y_std[...,0]]])
        tck_std = splrep(X,y_std,s=smooth_factor,k=spline_order)
        Y_std_smooth = splev(X_smooth,tck_std,der=0)

    color = color1

    axes.set_ylim(0.,1.)
    axes.autoscale(False)
    if filled:
        axes.fill_between(X,Y,color=color,alpha=0.1)
    axes.plot(X,Y,linewidth=1,color=color,alpha=0.2)

    if ytargets is None:
        ytargets = [0.5 for a in xrange(n_axes)]

    for a in xrange(n_axes):
        points = np.array(np.arange((a-0.5)*(n_points/n_axes),(a+0.5)*(n_points/n_axes)),int)%n_points
        theta = X_smooth[points[1:-1]]
        rect1 = ytargets[a]*np.ones_like(theta)
        rect2 = np.ones_like(theta)
        axes.fill(np.concatenate((theta,theta[::-1])),np.concatenate((rect1,(0.5*rect1+0.5*rect2)[::-1])),color='green',alpha=0.1)
        axes.fill(np.concatenate((theta,theta[::-1])),np.concatenate(((0.5*rect1+0.5*rect2),rect2[::-1])),color='green',alpha=0.3)

        for i, p in enumerate(points[1:]):
            value = np.minimum(Y_smooth[p]/(0.5+ytargets[a]/2),1.0)
            color = value*color1 + (1.-value)*color2
            if filled:
                axes.fill_between(X_smooth[p-1:p+1],Y_smooth[p-1:p+1],color=color,alpha=0.1)
            if a == 0 and i == 0:
                axes.plot(X_smooth[p-1:p+1],Y_smooth[p-1:p+1],color=color,linewidth=linewidth,label=label)
            else:
                axes.plot(X_smooth[p-1:p+1],Y_smooth[p-1:p+1],color=color,linewidth=linewidth)

            if y_std is not None:
                axes.plot(X_smooth[p-1:p+1],Y_smooth[p-1:p+1]+Y_std_smooth[p-1:p+1],color=color,linewidth=1,alpha=0.5)
                axes.plot(X_smooth[p-1:p+1],Y_smooth[p-1:p+1]-Y_std_smooth[p-1:p+1],color=color,linewidth=1,alpha=0.5)

    plt.thetagrids(X*180/np.pi,labels=None,frac=1.2)
    plt.rgrids(np.arange(1,11)/10., labels=None, angle=22.5)

    axes.set_xticklabels(xlabels,fontproperties=font,size=12)
    # axes.set_xticklabels(xlabels,fontproperties=font,size=12,rotation=0,rotation_mode="anchor",ha="center",y=1.5)
    axes.set_yticklabels([],fontproperties=font,size=12)
Ejemplo n.º 51
0
import matplotlib.pyplot as plt
import numpy as np
import pylab as pl

theta=np.arange(0,2*np.pi,0.02)

plt.subplot(121,polar=True)

plt.plot(theta,1.6*np.ones_like(theta),linewidth=2)
plt.plot(3*theta,theta/3,"--",linewidth=2)

plt.subplot(122,polar=True)
plt.plot(theta,1.4*np.cos(5*theta),"--",linewidth=2)
plt.plot(theta,1.8*np.cos(4*theta),linewidth=2)
plt.rgrids(np.arange(0.5,2,0.5),angle=45)
plt.thetagrids([0,45])
plt.show()
Ejemplo n.º 52
0
    def multirose(self, Gap=10,Width=1,Name='Dip'):
        """
        draw the rose map of multiple samples~
        """

        plt.figure(figsize=(self.Width, self.Height), dpi=self.Dpi)

        plt.axes(polar=True)
        plt.polar([0], [90])
        plt.xlim((0, 360))
        plt.ylim((0, 90))
        
        real_max=[]

        S=[]
        R=[]
        Color=[]
        Label=[]
        Whole={} 
        
        for i in range(len(self.raw)):
            S.append(self.raw.at[i, Name])
            
            if self.raw.at[i, 'Color'] not in Color and self.raw.at[i, 'Color']  !='':
                Color.append(self.raw.at[i, 'Color'])
            if self.raw.at[i, 'Label'] not in Label and self.raw.at[i, 'Label']  !='':
                Label.append(self.raw.at[i, 'Label'])

        Whole=({k: [] for k in Label})
        
        WholeCount=({k: [] for k in Label})
        
        
        for i in range(len(self.raw)):
            for k in Label:
                if self.raw.at[i, 'Label'] ==k:
                    Whole[k].append(self.raw.at[i, Name])
        

        t= tuple(np.linspace(0,360,360/Gap+1).tolist())
        real_max=0
        
        for j in range(len(Label)):
            
            for i in range(len(t)):
                tmp_count=0
                for u in Whole[Label[j]]:
                    if i < len(t)-1:
                        if t[i]<u<=t[i+1]:
                            tmp_count+=1
                real_max=max(real_max,tmp_count)
                WholeCount[Label[j]].append(tmp_count)
            
            
        maxuse=real_max
        R_factor = 90/maxuse
        
        for j in range(len(Label)):
            
            R=[]
            for i in WholeCount[Label[j]]:
                TMP=90- i *R_factor
                R.append(TMP)
            
            m,n=Polar().Trans(t,R)
            plt.plot(m, n, color=Color[j], linewidth=1, alpha=0.6, marker='',label=Label[j])
            plt.fill(m, n, Color=Color[j], Alpha=0.6)
                    
        

            
        list1 = [self.eqar(x) for x in range(0, 90, 15)]
        list2 = [str(x) for x in range(0, int(maxuse+1), int((maxuse+1)/7))]
        list2.reverse()
        plt.rgrids(list1, list2)
            
        
        plt.thetagrids(range(360 + 90, 0 + 90, -15), [str(x) for x in range(0, 360, 15)])

        plt.legend(loc=5, bbox_to_anchor=(1.5, 0.5))

        plt.savefig(self.name + "MultiRose.png", dpi=300)
        plt.savefig(self.name + "MultiRose.svg", dpi=300)
        plt.show()
Ejemplo n.º 53
0
plt.clf()

x = np.linspace(2 * np.pi * 27e1, 2 * np.pi * 50e4, 1000)
phi1 = np.arctan(1 / R * (L * x - 1 / (C * x)))
phi2 = -phi1
Z_theor = np.sqrt(R ** 2 + (L * x - 1 / (C * x)) ** 2)

plt.polar(phi1, Z_theor, "b", label="Theoriekurve")
plt.polar(phi2, Z_theor, "b")
plt.polar(arg, Z, "rx", label="Messwerte")
plt.ylim(0, 600)
plt.xlabel(r"$\varphi \,/\, \mathrm{rad}$")
plt.figtext(0.67, 0.68, r"$|Z| \,/\, \mathrm{\Omega}$")
plt.thetagrids(
    [0, 45, 90, 135, 180, 225, 270, 315],
    labels=[
        r"$0$",
        r"$\frac{1}{4} \pi$",
        r"$\frac{1}{2} \pi$",
        r"$\frac{3}{4} \pi$",
        r"$\pm \pi$",
        r"$- \frac{3}{4} \pi$",
        r"$- \frac{1}{2} \pi$",
        r"$- \frac{1}{4} \pi$",
    ],
)
plt.rgrids([200, 400, 600])
plt.legend(bbox_to_anchor=(0.45, 0.8, 0, 0))
plt.tight_layout()
plt.savefig("loesung-polar.pdf")
Ejemplo n.º 54
0
@author: LY
"""


import math
import numpy as np
import matplotlib.pyplot  as plt

import os, re





plt.figure(2)
theta = np.arange(0, 2*np.pi, 0.02)
#plt.subplot(polar= True)
plt.polar(theta, np.ones_like(theta), lw=2)
line2, = plt.polar(theta, np.cos(theta), '--' , lw=2, label = 'theorical')



plt.rgrids(np.arange(0.2,1,0.2),angle =130)
plt.thetagrids(np.linspace(0,330, 12))
plt.legend(handles = [line2],loc =4)
#plt.title('hi')
plt.show()


Ejemplo n.º 55
0
    def wulf(self, Width=1, Color='k'):
        """
        read the Excel, then draw the wulf net and Plot points, job done~
        """

        plt.figure(figsize=(self.Width, self.Height), dpi=self.Dpi)
        if ("csv" in self.name):
            raw = pd.read_csv(self.name)
        elif ("xlsx" in self.name):
            raw = pd.read_excel(self.name)

        Data = []
        Labels = []

        plt.axes(polar=True)
        plt.polar([0], [90])
        plt.xlim((0, 360))
        plt.ylim((0, 90))

        list1 = [self.eqan(x) for x in range(0, 90, 15)]
        list2 = [str(x) for x in range(0, 90, 15)]
        plt.rgrids(list1, list2)

        for i in range(len(raw)):
            Data.append([raw.at[i, "Name"], raw.at[i, "Dip"], raw.at[i, "Dip-Angle"], raw.at[i, "Color"],
                         raw.at[i, "Width"], raw.at[i, "Alpha"], raw.at[i, "Label"]])
            Dip = raw.at[i, "Dip"]
            Dip_Angle = raw.at[i, "Dip-Angle"]


            Label=raw.at[i, "Label"]
            if (Label not in Labels):
                Labels.append(Label)
            else:
                Label = ""
                
            Width = 1
            Color = 'red'
            Alpha = 0.8
            Marker = 'o'
            Size=50

            Setting=[Width,Color,Alpha,Marker,Size]

            Width = raw.at[i, "Width"]
            Color = raw.at[i, "Color"]
            Alpha = raw.at[i, "Alpha"]
            Marker = raw.at[i, "Marker"]
            Size=raw.at[i, "Size"]            
    
            if (Color not in Setting or Color != ""):
                Width = raw.at[i, "Width"]
                Color = raw.at[i, "Color"]
                Alpha = raw.at[i, "Alpha"]
                Marker = raw.at[i, "Marker"]
                Size=raw.at[i, "Size"]
                
                Setting=[Width,Color,Alpha,Marker,Size]
            r = np.arange(Dip - 90, Dip + 91, 1)
            BearR = [np.radians(-A + 90) for A in r]
            Line = (self.eqan(self.getangular(Dip_Angle, Dip, r)))

            plt.plot(BearR, Line, color=Color, linewidth=Width, alpha=Alpha, label=Label)

        plt.thetagrids(range(360 + 90, 0 + 90, -30), [str(x) for x in range(0, 360, 30)])
        plt.legend(loc=5, bbox_to_anchor=(1.5, 0.5))

        plt.savefig(self.name + "Wulff.png", dpi=300)
        plt.savefig(self.name + "Wulff.svg", dpi=300)
        plt.show()
Ejemplo n.º 56
0
    def schmidt(self, Width=1, Color='k'):
        """
        read the Excel, then draw the schmidt net and Plot points, job done~
        """
        plt.figure(figsize=(self.Width, self.Height), dpi=self.Dpi)
        if ("csv" in self.name):
            raw = pd.read_csv(self.name)
        elif ("xlsx" in self.name):
            raw = pd.read_excel(self.name)

        Data = []
        Labels = []
        plt.axes(polar=True)
        plt.polar([0], [90])
        plt.xlim((0, 360))
        plt.ylim((0, 90))

        list1 = [self.eqar(x) for x in range(0, 90, 15)]
        list2 = [str(x) for x in range(0, 90, 15)]
        plt.rgrids(list1, list2)

        for i in range(len(raw)):
            Data.append(
                [raw.at[i, "Name"], raw.at[i, "Dip"], raw.at[i, "Dip-Angle"], raw.at[i, "Color"],
                 raw.at[i, "Width"], raw.at[i, "Alpha"], raw.at[i, "Marker"], raw.at[i, "Label"]])
            Dip = raw.at[i, "Dip"]
            Dip_Angle = raw.at[i, "Dip-Angle"]

            Label = raw.at[i, "Label"]

            if (Label not in Labels):
                Labels.append(Label)
            else:
                Label = ""
                
                
            Width = 1
            Color = 'red'
            Alpha = 0.8
            Marker = 'o'
            Size=50

            Setting=[Width,Color,Alpha,Marker,Size]

            Width = raw.at[i, "Width"]
            Color = raw.at[i, "Color"]
            Alpha = raw.at[i, "Alpha"]
            Marker = raw.at[i, "Marker"]
            Size=raw.at[i, "Size"]            
    
            if (Color not in Setting or Color != ""):
                Width = raw.at[i, "Width"]
                Color = raw.at[i, "Color"]
                Alpha = raw.at[i, "Alpha"]
                Marker = raw.at[i, "Marker"]
                Size=raw.at[i, "Size"]
                
                Setting=[Width,Color,Alpha,Marker,Size]


            plt.scatter(np.radians(90 - Dip), self.eqar(Dip_Angle), marker=Marker, s=Size, color=Color, alpha=Alpha,
                    label=Label, edgecolors='black')
        
        # plt.plot(120, 30, color='K', linewidth=4, alpha=Alpha, marker='o')
        plt.thetagrids(range(360 + 90, 0 + 90, -30), [str(x) for x in range(0, 360, 30)])

        plt.legend(loc=5, bbox_to_anchor=(1.5, 0.5))

        plt.savefig(self.name + "Schmidt.png", dpi=300)
        plt.savefig(self.name + "Schmidt.svg", dpi=300)
        plt.show()
Ejemplo n.º 57
0
# x = np.arange(.1, 1000, .01)
# plt.plot(x, z_von_f(x, 50, 2, .01), "k-")
# plt.xscale("log")
# plt.ylabel(r"$|z|\,[\mathrm{\Omega}]$")
# plt.xlabel(r"$f\,[\mathrm{Hz}]$")

# fig = plt.gcf() #Gibt Referent auf die aktuelle Figur - "get current figure"
# fig.set_size_inches(9, 6)

# plt.grid(which = 'both')
# plt.savefig('../img/z_f.pdf', bbox_inches='tight')
# plt.clf()

theta = np.arange(0, 2 * np.pi + .1, .01)
angels = np.arange(0, 360, 45)
for i in range(5):
	plt.polar(theta, (i+1) + 0 * theta, "k-")
plt.thetagrids(angels)
rmax = np.arange(.001, i+1, .01)
for ang in angels:
	plt.polar(ang * (np.pi / 180) + 0 * rmax, rmax, "k-")

meintheta = np.arange(-np.pi/4, np.pi/4, .01)
plt.polar(meintheta, 3.5 / np.cos(meintheta), "r-")

fig = plt.gcf() #Gibt Referent auf die aktuelle Figur - "get current figure"
fig.set_size_inches(9, 6)

plt.grid(which = 'both')
plt.savefig('../img/z_phi.pdf', bbox_inches='tight')
plt.clf()
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.family'] = 'SimHei'
matplotlib.rcParams['font.sans-serif'] = ['SimHei']
labels = np.array(['综合', 'KDA', '发育', '推进', '生存', '输出'])
nAttr = 6
data = np.array([7, 5, 6, 9, 8, 7]) #数据值
angles = np.linspace(0, 2*np.pi, nAttr, endpoint=False)
data = np.concatenate((data, [data[0]]))
angles = np.concatenate((angles, [angles[0]]))
fig = plt.figure(facecolor="white")
plt.subplot(111, polar=True)
plt.plot(angles, data, 'bo-', color ='g', linewidth=2)
plt.fill(angles, data, facecolor='g', alpha=0.25)
plt.thetagrids(angles*180/np.pi, labels)
plt.figtext(0.52, 0.95, 'DOTA能力值雷达图', ha='center')
plt.grid(True)
plt.show()
Ejemplo n.º 59
0
#plt.semilogy(w, p, lw=2)
##plt.ylim(0, 1.5)
#plt.xlabel('x')
#plt.ylabel('log(y)')
#
#plt.subplot(224)
#plt.loglog(w,p,lw=2)
#plt.xlabel('log(x)')
#plt.ylabel('log(y)')
#
#plt.show()


plt.figure(2)
theta = np.arange(0, 2*np.pi, 0.02)
plt.subplot(121, polar= True)
plt.plot(theta, 2*np.ones_like(theta), lw=2)
plt.plot(theta, theta/6, '--' , lw=2)

plt.subplot(122, polar = True)
plt.plot(theta, np.cos(5*theta),'--', lw=2)
#plt.plot(theta, np.sin(5*theta),'--', lw=2)
plt.plot(theta, 2*np.cos(4*theta),lw=2)
plt.rgrids(np.arange(0.4,2,0.4),angle =130)
plt.thetagrids([0,45,90])
plt.show()

plt.figure(3)
theta1 = np.arange(0, 2*np.pi, 0.01)
plt.plot(polar = True)
plt.plot(theta1, np.cos(2*theta1))