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

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

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

等值線圖的Python繪制方法

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

雖然看起來復雜,其實用matplotlib實現(xiàn)起來并不難。

代碼如下:

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è)增加圖例作為圖表中所用顏色的說明幾乎是必需的,在上述代碼最后增加colorbar()函數(shù)就可以實現(xiàn)。

plt.colorbar()

python等值線圖繪制,計算合適的等值線間距

python按照給定坐標點進行插值并繪制等值線圖

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):
	# 計算較為合適的gap來獲取最終的分界值
    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):
	# 直接按照分組字數(shù)計算分界值
    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)

    # 輸出為二進制流
    canvas = fig.canvas
    buffer = io.BytesIO()  # 獲取輸入輸出流對象
    canvas.print_png(buffer)  # 將畫布上的內(nèi)容打印到輸入輸出流對象
    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)格坐標點
    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)格坐標點和對應(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,  # 間距,標簽
        'xy_msg': [(min_x, max_x), (min_y, max_y)],  # 邊界坐標
        'plot_data': data,  # 繪圖點數(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é)

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

相關(guān)文章

  • Python3 JSON編碼解碼方法詳解

    Python3 JSON編碼解碼方法詳解

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

    Django logging配置及使用詳解

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

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

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

    python常用庫之NumPy和sklearn入門

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

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

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

    Python函及模塊的使用

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

    如何用itertools解決無序排列組合的問題

    下面小編就為大家?guī)硪黄绾斡胕tertools解決無序排列組合的問題。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    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,好像又加入了不少黑魔法!由于暫時不能使用 apt-get 的方式安裝 Python 3.6,所以還是直接編譯源碼安裝吧。下面這篇文章就介紹了在Ubuntu 16.04 LTS中源碼安裝Python 3.6.0的方法教程,需要的朋友可以參考下。
    2016-12-12
  • Python?socket如何解析HTTP請求內(nèi)容

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

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

    python輪詢機制控制led實例

    這篇文章主要介紹了python輪詢機制控制led實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-05-05

最新評論

嵊州市| 阳西县| 布拖县| 洪湖市| 湘乡市| 桃园县| 平南县| 波密县| 安岳县| 马龙县| 墨竹工卡县| 松江区| 灵武市| 卢湾区| 柘城县| 襄汾县| 长兴县| 云龙县| 东乡族自治县| 中江县| 鄱阳县| 新绛县| 耒阳市| 大足县| 绥芬河市| 甘德县| 开平市| 罗甸县| 方正县| 武安市| 略阳县| 含山县| 阿城市| 普陀区| 吉安市| 雷州市| 交城县| 乐清市| 开江县| 泾源县| 宁城县|