欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

解讀等值線圖的Python繪制方法

 更新時(shí)間:2023年02月01日 09:55:16   作者:Jeremy_lf  
這篇文章主要介紹了解讀等值線圖的Python繪制方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

等值線圖的Python繪制方法

等值線圖或等高線圖在科學(xué)界經(jīng)常用到,它是由一些封閉的曲線組成的,來(lái)表示三維結(jié)構(gòu)表面。

雖然看起來(lái)復(fù)雜,其實(shí)用matplotlib實(shí)現(xiàn)起來(lái)并不難。

代碼如下:

import numpy as np
import matplotlib.pyplot as plt
dx=0.01;dy=0.01
x=np.arange(-2.0,2.0,dx)
y=np.arange(-2.0,2.0,dy)
X,Y=np.meshgrid(x,y)
def f(x,y):
    return(1-y**5+x**5)*np.exp(-x**2-y**2)
C=plt.contour(X,Y,f(X,Y),8,colors='black')  #生成等值線圖
plt.contourf(X,Y,f(X,Y),8)
plt.clable(C,inline=1,fontsize=10)

結(jié)果如下:

使用等值線圖,在圖的一側(cè)增加圖例作為圖表中所用顏色的說(shuō)明幾乎是必需的,在上述代碼最后增加colorbar()函數(shù)就可以實(shí)現(xiàn)。

plt.colorbar()

python等值線圖繪制,計(jì)算合適的等值線間距

python按照給定坐標(biāo)點(diǎn)進(jìn)行插值并繪制等值線圖

import matplotlib.pyplot as plt
import numpy as np
import math
import pandas as pd
import io
import copy

def get_gap(gap):
    gap = str(gap)
    gap_len = len(gap)
    gap_list = list(map(int, gap))
    top_value = int(gap_list[0])

    gap_bottom = top_value * (10 ** (gap_len - 1))
    gap_mid = gap_bottom + int((10 ** (gap_len - 1) / 2))
    gap_top = (top_value + 1) * (10 ** (gap_len - 1))
    gap_value = [gap_bottom, gap_mid, gap_top]

    gap_bottom_dis = abs(int(gap) - gap_bottom)
    gap_mid_dis = abs(int(gap) - gap_mid)
    gap_top_dis = abs(int(gap) - gap_top)
    range_list = [gap_bottom_dis, gap_mid_dis, gap_top_dis]

    min_i = 0
    for i in range(len(range_list)):
        if range_list[i] < range_list[min_i]:
            min_i = i
    final_gap = gap_value[min_i]
    return int(final_gap)

def interpolation(lon, lat, lst):
    # 網(wǎng)格插值——反距離權(quán)重法
    p0 = [lon, lat]
    sum0 = 0
    sum1 = 0
    temp = []

    for point in lst:
        if lon == point[0] and lat == point[1]:
            return point[2]
        Di = distance(p0, point)

        ptn = copy.deepcopy(point)
        ptn = list(ptn)
        ptn.append(Di)
        temp.append(ptn)

    temp1 = sorted(temp, key=lambda point: point[3])

    for point in temp1[0:15]:
        sum0 += point[2] / math.pow(point[3], 2)
        sum1 += 1 / math.pow(point[3], 2)
    return sum0 / sum1

def distance(p, pi):
    dis = (p[0] - pi[0]) * (p[0] - pi[0]) + (p[1] - pi[1]) * (p[1] - pi[1])
    m_result = math.sqrt(dis)
    return m_result

def gap_equal_line_value(min_value, max_value , n_group):
	# 計(jì)算較為合適的gap來(lái)獲取最終的分界值
    n_group = int(n_group)
    gap = abs((max_value - min_value) / n_group)

    if gap >= 1:
        gap = int(math.ceil(gap))
        final_gap = get_gap(gap)
    else:
        gap_effect = np.float('%.{}g'.format(1) % Decimal(gap))
        gap_effect = gap * (10 ** (len(str(gap_effect)) - 2))
        gap_multi = gap_effect / gap
        gap = math.ceil(gap_effect)
        final_gap = get_gap(gap)
        final_gap = final_gap / gap_multi
    #final_gap = np.float('%.{}g'.format(4) % Decimal(final_gap))

    bottom = min_value + final_gap

    if final_gap < 1:
        final_bottom = bottom
    else:
        if abs(bottom) >= 1:
            bottom_effect = math.ceil(abs(bottom))
            final_bottom = get_gap(bottom_effect)
        else:
            bottom_effect = np.float('%.{}g'.format(1) % (abs(bottom)))
            bottom_multi = bottom_effect / (abs(bottom))
            bottom_effect = math.ceil(bottom_effect)
            final_bottom = get_gap(bottom_effect)
            final_bottom = (final_bottom / bottom_multi)

        if bottom < 0:
            final_bottom = final_bottom * (-1)
        else:
            pass
    # print(final_bottom)
    #final_bottom = keep_decimal(final_bottom)
    equal_line_value = []
    if math.floor(min_value) >= final_bottom:
        equal_line_value.append(final_bottom-1)
    else:
        equal_line_value.append(math.floor(min_value))
    equal_line_value.append(final_bottom)

    for i in range(1, n_group-1):
        final_bottom = final_bottom + final_gap
        equal_line_value.append(final_bottom)
    final_bottom = final_bottom + final_gap
    if final_bottom <= max_value:
        equal_line_value.append(math.ceil(max_value))
    else:
        equal_line_value.append(final_bottom)
    print(equal_line_value)
    return equal_line_value


def equal_line_value(min_value, max_value, n_group):
	# 直接按照分組字?jǐn)?shù)計(jì)算分界值
    n_group = int(n_group)
    gap = abs((max_value - min_value) / n_group)

    equal_line_value = []
    if gap <= 0:
        gap_flag = False #gap為0
        equal_line_value.append(max_value-1)
        equal_line_value.append(max_value+1)
    else:
        gap_flag = True
        equal_line_value.append(min_value)
        now_value = min_value
        for i in range(1, n_group):
            now_value = now_value + gap
            equal_line_value.append(now_value)
        equal_line_value.append(max_value)
    res = {
        'gap_flag': gap_flag,
        'equal_line_value': equal_line_value
    }

    return res



def contour_line_plot(grid_x_plot, grid_y_plot, f_plot, levels,x_long,y_long,n_group):
    n_group = int(n_group)

    color1 = '#74E3AD'
    color2 = '#17BD6D'
    color3 = '#05A156'
    color4 = '#038A49'
    color5 = '#165C3A'
    color6 = '#BDBDBD'
    color7= '#848484'
    color8 = '#FA58F4'
    color9 = '#FF00BF'
    color10 = '#FF0080'
    color11 = '#8A084B'
    color12 = '#3B0B24'

    Colors_all = (color1, color2, color3, color4, color5, color6, color7, color8, color9, color10, color11, color12)

    Colors = Colors_all[0:n_group]

    fig = plt.figure(figsize=(x_long,y_long))
    ax = plt.subplot()

    ax.contourf(grid_x_plot, grid_y_plot, f_plot, levels=levels, colors = Colors)

    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.spines['bottom'].set_visible(False)
    ax.spines['left'].set_visible(False)

    ax.set_xticks([])
    ax.set_yticks([])
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
    plt.margins(0, 0)

    # 輸出為二進(jìn)制流
    canvas = fig.canvas
    buffer = io.BytesIO()  # 獲取輸入輸出流對(duì)象
    canvas.print_png(buffer)  # 將畫布上的內(nèi)容打印到輸入輸出流對(duì)象
    data = buffer.getvalue()  # 獲取流的值
    buffer.close()
    plt.close()
    # with open('hhh.png', mode='wb') as f:
    #     f.write(data)

    return data


def contour_line(data,n_group):
    '''
    data:數(shù)組,[[x1,y1,value1],[x2,y2,value2],[x2,y2,value2],......]
    例:data = [[5,5,11],[5,25,21],[10,25,45],[10,5,5],[8,5,60]]
    n_group:分組組數(shù)
    '''
    data = pd.DataFrame(data,columns=['x', 'y', 'f'])

    min_x = data['x'].min()
    max_x = data['x'].max()
    min_y = data['y'].min()
    max_y = data['y'].max()

    # 設(shè)置等值線圖大小
    x_long = 40.0
    y_long = 40.0

    lst = data.iloc[:, 0:3].values
    # 設(shè)置網(wǎng)格大小
    n_grid = 50
    grid_x = np.linspace(min_x, max_x, n_grid)
    grid_y = np.linspace(min_y, max_y, n_grid)

    # 得到所有網(wǎng)格坐標(biāo)點(diǎn)
    data_xy_list = []
    for i in range(len(grid_x)):
        for j in range(len(grid_y)):
            data_xy_list.append([grid_x[i], grid_y[j]])
    data_xy = pd.DataFrame(data_xy_list, columns=['x', 'y'])

    # 得到所有網(wǎng)格坐標(biāo)點(diǎn)和對(duì)應(yīng)的值
    insert_value_list = []
    for i in range(len(data_xy)):
        value = interpolation(data_xy.iloc[i, 0], data_xy.iloc[i, 1], lst)
        insert_value_list.append([data_xy.iloc[i, 0], data_xy.iloc[i, 1], value])

    insert_data = pd.DataFrame(insert_value_list, columns=['x', 'y', 'f'])

    # 得到等值線的分界值
    equal_value_res = equal_line_value(insert_data.loc[:, ['f']].min()[0], insert_data.loc[:, ['f']].max()[0],n_group)
    equal_value_list = equal_value_res['equal_line_value']

    f_plot = insert_data.loc[:, ['f']].values.reshape(n_grid, n_grid)
    grid_y_plot, grid_x_plot = np.meshgrid(grid_y, grid_x)

    plt_msg = contour_line_plot(grid_x_plot, grid_y_plot, f_plot, equal_value_list,x_long,y_long,n_group)
    #data = data.set_index(axis.index)

    if equal_value_res['gap_flag'] == False:
        equal_value_list = [insert_data.loc[:, ['f']].min()[0]-1, insert_data.loc[:, ['f']].min()[0]]

    res = {
        # 等值線圖
        'plt_msg': plt_msg, # 等值線圖數(shù)據(jù)流
        'equal_value_list': equal_value_list,  # 間距,標(biāo)簽
        'xy_msg': [(min_x, max_x), (min_y, max_y)],  # 邊界坐標(biāo)
        'plot_data': data,  # 繪圖點(diǎn)數(shù)據(jù)
        'plot_size': [x_long, y_long]
    }

    return res


if __name__ == "__main__":

    res = contour_line([[5, 5, 11], [5, 25, 21], [10, 25, 45], [10, 5, 5], [8, 5, 60]], 5)

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

  • Python使用multiprocessing模塊實(shí)現(xiàn)多進(jìn)程并發(fā)處理大數(shù)據(jù)量的示例代碼

    Python使用multiprocessing模塊實(shí)現(xiàn)多進(jìn)程并發(fā)處理大數(shù)據(jù)量的示例代碼

    這篇文章主要介紹了Python使用multiprocessing模塊實(shí)現(xiàn)多進(jìn)程并發(fā)處理大數(shù)據(jù)量的示例代碼,本文通過(guò)示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友參考下吧
    2024-01-01
  • 在tensorflow中設(shè)置保存checkpoint的最大數(shù)量實(shí)例

    在tensorflow中設(shè)置保存checkpoint的最大數(shù)量實(shí)例

    今天小編就為大家分享一篇在tensorflow中設(shè)置保存checkpoint的最大數(shù)量實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-01-01
  • Python第三方庫(kù)之OpenCV庫(kù)的實(shí)用指南

    Python第三方庫(kù)之OpenCV庫(kù)的實(shí)用指南

    OpenCV(Open Source Computer Vision Library)作為一個(gè)強(qiáng)大的計(jì)算機(jī)視覺(jué)庫(kù),提供了豐富的圖像處理和計(jì)算機(jī)視覺(jué)功能,本文將帶領(lǐng)讀者使用Python編程語(yǔ)言,通過(guò)簡(jiǎn)單的代碼示例,初步掌握OpenCV的圖像處理技術(shù),需要的朋友可以參考下
    2024-09-09
  • python批量更改目錄名/文件名的方法

    python批量更改目錄名/文件名的方法

    這篇文章主要介紹了python批量更改目錄名/文件名的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2021-04-04
  • Python線程之如何解決共享變量問(wèn)題

    Python線程之如何解決共享變量問(wèn)題

    這篇文章主要介紹了Python線程之如何解決共享變量問(wèn)題,掐滅問(wèn)我們學(xué)習(xí)了銀行轉(zhuǎn)賬的這個(gè)場(chǎng)景,本文解決上次多個(gè)線程的操作都更改了amount變量導(dǎo)致運(yùn)行結(jié)果不對(duì)的問(wèn)題,需要的朋友可以參考一下
    2022-02-02
  • Python使用pandasai實(shí)現(xiàn)數(shù)據(jù)分析

    Python使用pandasai實(shí)現(xiàn)數(shù)據(jù)分析

    本文主要介紹了Python使用pandasai實(shí)現(xiàn)數(shù)據(jù)分析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2023-06-06
  • 深入Python函數(shù)編程的一些特性

    深入Python函數(shù)編程的一些特性

    這篇文章主要介紹了更為深入的Python函數(shù)編程的一些特性,本文來(lái)自于IBM官方開(kāi)發(fā)者技術(shù)文檔,需要的朋友可以參考下
    2015-04-04
  • python @propert裝飾器使用方法原理解析

    python @propert裝飾器使用方法原理解析

    這篇文章主要介紹了python @propert裝飾器使用方法原理解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-12-12
  • Python?matplotlib實(shí)戰(zhàn)之散點(diǎn)圖繪制

    Python?matplotlib實(shí)戰(zhàn)之散點(diǎn)圖繪制

    散點(diǎn)圖,又名點(diǎn)圖、散布圖、X-Y圖,是將所有的數(shù)據(jù)以點(diǎn)的形式展現(xiàn)在平面直角坐標(biāo)系上的統(tǒng)計(jì)圖表,本文主要為大家介紹了如何使用Matplotlib繪制散點(diǎn)圖,需要的可以參考下
    2023-08-08
  • Python數(shù)據(jù)分析之如何利用pandas查詢數(shù)據(jù)示例代碼

    Python數(shù)據(jù)分析之如何利用pandas查詢數(shù)據(jù)示例代碼

    查詢和分析數(shù)據(jù)是pandas的重要功能,也是我們學(xué)習(xí)pandas的基礎(chǔ),下面這篇文章主要給大家介紹了關(guān)于Python數(shù)據(jù)分析之如何利用pandas查詢數(shù)據(jù)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),需要的朋友可以參考借鑒,下面來(lái)一起看看吧。
    2017-09-09

最新評(píng)論