如何在python中csv文件生成的二维热图上叠加梯度场?

2024-03-29 08:46:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个从csv文件生成的热图,如下:enter image description here

现在我需要在上面叠加一个梯度场。我试过了数值梯度,但它的工作并不完美。这是我试过的python代码。你知道吗

import csv
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns



data_path = 'sed2.csv' # this is a two dimensional array with 51 row and 47 columns
with open(data_path, 'r') as f:
    reader = csv.reader(f, delimiter=',')
    # get header from first row
    headers = next(reader)
    # get all the rows as a list
    data = list(reader)
    # transform data into numpy array
    data = np.array(data).astype(float)

#print(headers)
#print(data.shape)
#print(data[:,1:47])
[gx,gy]=np.gradient(np.array(data[:,1:47], dtype=float)) # here I calculated the gradient from a 51x47 matrix 


plt.rcParams['font.size'] = 30
df=pd.read_csv('n_vs_c_sed.csv') # this reads file with heading: n c sed

df_pivot=df.pivot('c', 'n', 'sed')
fig = plt.figure(figsize=(10,10))
ax = fig.add_subplot(111)
sns.heatmap(df_pivot, cmap='RdGy',  annot=False,  square=True, cbar=True, xticklabels=15, yticklabels=10)
ax.set_yticklabels(ax.get_yticklabels(), rotation=0)

for _, spine in ax.spines.items():
    spine.set_visible(True)
    spine.set_linewidth(1.0)
plt.gca().invert_yaxis()
ax.set_aspect(aspect=.9)
plt.savefig('SED.png', dpi = 300, transparent = True, bbox_inches = 'tight', pad_inches = 0)
#plt.contour(df_pivot, 15, colors='black')
n = np.linspace(5,50,46)
c= np.linspace(0,.5,20)
X,Y = np.meshgrid(n,c)
plt.quiver(X,Y,gy,gx,width=.003,linewidth=1)
plt.show()

我从中得到的结果是here,这不是预期的。但是,如果我只运行quiver plot的代码,如下所示:

import csv
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns

fig = plt.figure(figsize=(10,10))
data_path = 'sed2.csv'
with open(data_path, 'r') as f:
    reader = csv.reader(f, delimiter=',')
    # get header from first row
    headers = next(reader)
    # get all the rows as a list
    data = list(reader)
    # transform data into numpy array
    data = np.array(data).astype(float)



   #print(headers)
#print(data.shape)
#print(data[:,1:47])
[gx,gy]=np.gradient(np.array(data[:,1:47], dtype=float))
dx = np.linspace(5,50,46)
dy= np.linspace(0,.5,20)
X,Y = np.meshgrid(dx,dy)
#u,v=np.meshgrid(gx,gy)
plt.quiver(X,Y,gy,gx,width=.002,linewidth=0.5)
plt.show()

它给出了图like this。 任何建议都将不胜感激。谢谢。你知道吗


Tags: csvimportnumpydfdatagetasnp