最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

解讀等值線圖的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)  # 將畫(huà)布上的內(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)文章

  • Python3 JSON編碼解碼方法詳解

    Python3 JSON編碼解碼方法詳解

    這篇文章主要介紹了Python3 JSON編碼解碼方法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-09-09
  • Django logging配置及使用詳解

    Django logging配置及使用詳解

    這篇文章主要介紹了Django logging配置及使用詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2019-07-07
  • Python內(nèi)置函數(shù)input()示例詳解

    Python內(nèi)置函數(shù)input()示例詳解

    input()函數(shù)是Python中用于獲取用戶(hù)輸入的一個(gè)簡(jiǎn)單而強(qiáng)大的工具,它在創(chuàng)建需要用戶(hù)交互的程序時(shí)非常有用,這篇文章主要介紹了Python內(nèi)置函數(shù)input()詳解,需要的朋友可以參考下
    2024-04-04
  • python常用庫(kù)之NumPy和sklearn入門(mén)

    python常用庫(kù)之NumPy和sklearn入門(mén)

    這篇文章主要介紹了python常用庫(kù)之NumPy和sklearn入門(mén),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2019-07-07
  • python3實(shí)現(xiàn)短網(wǎng)址和數(shù)字相互轉(zhuǎn)換的方法

    python3實(shí)現(xiàn)短網(wǎng)址和數(shù)字相互轉(zhuǎn)換的方法

    這篇文章主要介紹了python3實(shí)現(xiàn)短網(wǎng)址和數(shù)字相互轉(zhuǎn)換的方法,涉及Python操作字符串的相關(guān)技巧,非常具有實(shí)用價(jià)值,需要的朋友可以參考下
    2015-04-04
  • Python函及模塊的使用

    Python函及模塊的使用

    這篇文章主要介紹了Python函及模塊的使用,基本函數(shù)包括定義函數(shù)、函數(shù)的參數(shù)、用模塊管理函數(shù)等一些基本定義,下面文章不僅對(duì)這些又說(shuō)描述,還有變量的作用域的詳細(xì)內(nèi)容,需要的朋友可以參考一下,希望對(duì)你有所幫助
    2021-11-11
  • 如何用itertools解決無(wú)序排列組合的問(wèn)題

    如何用itertools解決無(wú)序排列組合的問(wèn)題

    下面小編就為大家?guī)?lái)一篇如何用itertools解決無(wú)序排列組合的問(wèn)題。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧
    2017-05-05
  • Ubuntu 16.04 LTS中源碼安裝Python 3.6.0的方法教程

    Ubuntu 16.04 LTS中源碼安裝Python 3.6.0的方法教程

    最近Python 3發(fā)布了新版本Python 3.6.0,好像又加入了不少黑魔法!由于暫時(shí)不能使用 apt-get 的方式安裝 Python 3.6,所以還是直接編譯源碼安裝吧。下面這篇文章就介紹了在Ubuntu 16.04 LTS中源碼安裝Python 3.6.0的方法教程,需要的朋友可以參考下。
    2016-12-12
  • Python?socket如何解析HTTP請(qǐng)求內(nèi)容

    Python?socket如何解析HTTP請(qǐng)求內(nèi)容

    這篇文章主要介紹了Python?socket如何解析HTTP請(qǐng)求內(nèi)容,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-02-02
  • python輪詢(xún)機(jī)制控制led實(shí)例

    python輪詢(xún)機(jī)制控制led實(shí)例

    這篇文章主要介紹了python輪詢(xún)機(jī)制控制led實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2020-05-05

最新評(píng)論

乡城县| 广水市| 沁阳市| 开原市| 景德镇市| 堆龙德庆县| 晋江市| 成安县| 兰考县| 射洪县| 鹰潭市| 洛浦县| 仁怀市| 海门市| 宜昌市| 景谷| 驻马店市| 隆子县| 崇文区| 灌云县| 滨州市| 井研县| 舞阳县| 延寿县| 班戈县| 铜川市| 花垣县| 太和县| 朝阳市| 分宜县| 句容市| 阿克| 江北区| 张家界市| 徐州市| 喀喇| 荆门市| 谷城县| 高碑店市| 五原县| 慈利县|