我有以下格式的 df:
df = pd.DataFrame({'col1':[11,12,23,21,23,43,23,12,21,34],
'col2':[111,121,213,211,123,143,213,122,210,171],
'col3':[2111,2121,2213,2121,3123,4143,3213,2122,1210,989],
'name':['aa','bb','cc','cc','aa','aa','cc','bb','aa','bb']})
这是我使用 Plotly 创建简单等高线图的代码:
x = np.array(df['col1'])
y = np.array(df['col2'])
z = np.array(df['col3'])
xi = np.linspace(x.min(), x.max(), 100)
yi = np.linspace(y.min(), y.max(), 100)
grid_x, grid_y = np.meshgrid(xi,yi)
Z = griddata((x,y), z, (grid_x, grid_y), method='linear')
fig = go.Figure(go.Contour(x=xi, y=yi, z=Z, colorscale='Jet'))
fig.show()
此等高线图是所有
name
值的单个图。我想创建按 name
列分组的类似等高线图。这意味着,在这个例子中,它应该为每个 'aa'
、'bb'
和 'cc'
值绘制 3 个等高线图。
由于您只想获取“名称”中具有特定值的行,因此对于该列中的每个唯一值,请执行以下操作:
for name in np.unique(df['name']):
subdf = df[df['name'] == name]
x = np.array(subdf['col1'])
y = np.array(subdf['col2'])
z = np.array(subdf['col3'])
# ...
此外,作为旁注,您可以包含导入以使您的代码更具可重现性。
import pandas as pd
import numpy as np
from scipy.interpolate import griddata
import plotly.graph_objects as go
你可以试试:
groups = df.groupby('name')
# loop over each group
for name, group in groups:
x = np.array(group['col1'])
y = np.array(group['col2'])
z = np.array(group['col3'])
xi = np.linspace(x.min(), x.max(), 100)
yi = np.linspace(y.min(), y.max(), 100)
grid_x, grid_y = np.meshgrid(xi,yi)
Z = griddata((x,y), z, (grid_x, grid_y), method='linear')
fig = go.Figure(go.Contour(x=xi, y=yi, z=Z, colorscale='Jet'))
fig.update_layout(title=name)
fig.show()