有人可以帮助我吗?我想绘制一个等高线图,下面以我的数据为例。我在csv文件中有4天的高度数据和温度数据:
date 1 date 2 date 3 date 4
height temp height temp height temp height temp
9.3 28.0 8.7 27.6 10.0 26.0 9.5 26.8
9.7 27.3 9.3 26.8 12.8 25.5 10.8 25.9
10.0 26.8 10.8 25.9 13.1 25.3 11.4 25.0
10.6 26.5 12.7 24.4 14.8 24.7 12.9 24.2
12.8 26.0 13.5 23.8 15.2 24.3 13.6 23.4
13.3 25.7 17.8 22.7 16.8 23.7 14.0 22.6
16.8 25.4 18.9 22.4 17.9 23.3 14.7 22.0
17.2 24.6 20.0 21.0 18.6 23.0 15.9 21.3
这是我的脚本尝试过的:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
import csv
import glob
import os
path = "C:/Users/SYIFAAZRA/Documents/belajar_wradlib/Skew-T/New/"
os.chdir(path)
filenames = glob.glob("*.csv")
dfs = []
for f in filenames:
col_names = ['height', 'temp']
df = pd.read_csv(f, delimiter=',',skiprows=7, usecols=[11, 21], names=col_names, na_values=['----'])
df = df.dropna()
max = df.height.idxmax()
min = df.height.idxmin()
df = df.loc[min:max, :]
dfs.append(df)
df2 = pd.concat(dfs, ignore_index=False, axis=1)
fig = plt.figure()
ax = fig.add_subplot(111)
x = np.linspace(0,100, 50)
y = df['height']
X,Y = np.meshgrid(x, y)
Z = df['temp']
plt.show()
我想绘制一个等高线图,其中x =日期数,y =高度数据,z =温度数据。有人可以建议我如何解决上面的脚本。
答案 0 :(得分:0)
首先,它有助于呈现一种生成数据的方法,而不是将其粘贴:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
d = {('date1', 'height'): {0: 9.3, 1: 9.7, 2: 10.0, 3: 10.6, 4: 12.8, 5: 13.3, 6: 16.8, 7: 17.2},
('date1', 'temp'): {0: 28.0, 1: 27.3, 2: 26.8, 3: 26.5, 4: 26.0, 5: 25.7, 6: 25.4, 7: 24.6},
('date2', 'height'): {0: 8.7, 1: 9.3, 2: 10.8, 3: 12.7, 4: 13.5, 5: 17.8, 6: 18.9, 7: 20.0},
('date2', 'temp'): {0: 27.6, 1: 26.8, 2: 25.9, 3: 24.4, 4: 23.8, 5: 22.7, 6: 22.4, 7: 21.0},
('date3', 'height'): {0: 10.0, 1: 12.8, 2: 13.1, 3: 14.8, 4: 15.2, 5: 16.8, 6: 17.9, 7: 18.6},
('date3', 'temp'): {0: 26.0, 1: 25.5, 2: 25.3, 3: 24.7, 4: 24.3, 5: 23.7, 6: 23.3, 7: 23.0},
('date4', 'height'): {0: 9.5, 1: 10.8, 2: 11.4, 3: 12.9, 4: 13.6, 5: 14.0, 6: 14.7, 7: 15.9},
('date4', 'temp'): {0: 26.8, 1: 25.9, 2: 25.0, 3: 24.2, 4: 23.4, 5: 22.6, 6: 22.0, 7: 21.3}}
然后,我们需要重塑您的数据,以便将高度和日期作为行/列名称,然后将temp作为值(2D数组)。另外,我们将日期转换为整数。
df = df.melt()
height_data = df[df.variable_1=='height'].reset_index(drop=True).copy()
temp_data = df[df.variable_1=='temp'].reset_index(drop=True).copy()
df = pd.DataFrame({'date': height_data.variable_0.str[4:].astype('int'),
'height': height_data.value, 'temp': temp_data.value})
我们旋转数据框以获得所需形状:
df = df.pivot('date', 'height').fillna(0)
X = df.columns.get_level_values(1)
Y = df.index.values
Z = df.values
Xi,Yi = np.meshgrid(X, Y)
plt.contour(Xi, Yi, Z, 20, cmap='RdGy')
给我们这个结果:
其中x轴是day
,y轴是height
,值是温度-f(x,y)
的结果,其中x = day,y = temperature。< / p>