首页 > 解决方案 > 非矩形网格上的填充等高线图

问题描述

我在 matplotlib 中有以下等高线图

import numpy as np
import matplotlib.pyplot as plt

x = np.array([[1,2,3], [2,3,4], [3,4,5]])
y = np.array([[9,8,6], [10,9,7], [11,10,8]])
z = np.array([[80,90,80], [85,100,90], [80,90,80]])

fig, ax1 = plt.subplots()
cont = ax1.contourf(x, y, z)
cbar = fig.colorbar(cont)
plt.plot(x[0,:], y[0,:], '-ok')
plt.plot(x[1,:], y[1,:], '-ok')
plt.plot(x[2,:], y[2,:], '-ok')

正确的

我正在尝试转换为 plotly 以便在 Web 浏览器中有一个交互式图形。我设法使用plotly在矩形xy网格上创建等高线图,但是是否可以像matplotlib的contourf一样使用x、y、z的完整网格网格?下面的情节代码不起作用:

import numpy as np
import plotly.graph_objects as go
x = np.array([[1,2,3], [2,3,4], [3,4,5]])
y = np.array([[9,8,6], [10,9,7], [11,10,8]])
z = np.array([[80,90,80], [85,100,90], [80,90,80]])
contourdata = go.Contour(x=x, y=y, z=z)
fig = go.Figure(data = contourdata)
fig.add_trace(go.Scatter(x=x[0,:], y=y[0,:], mode='lines+markers',line=dict(color='black')))
fig.add_trace(go.Scatter(x=x[1,:], y=y[1,:], mode='lines+markers',line=dict(color='black')))
fig.add_trace(go.Scatter(x=x[2,:], y=y[2,:], mode='lines+markers',line=dict(color='black')))
fig.write_html('test.html', auto_open=True)

错误的

我可以使用 mpld3,但我不想这样做。如果情节不支持这一点,是否有更好的选择?

标签: pythonmatplotlibplotlyplotly-python

解决方案


我发现我一直在寻找的功能不是 Contour 而是 Contourcarpet https://plot.ly/python/carpet-contour/

import numpy as np
import plotly.graph_objects as go

x = np.array([[1,2,3], [2,3,4], [3,4,5]])
y = np.array([[9,8,6], [10,9,7], [11,10,8]])
z = np.array([[80,90,80], [85,100,90], [80,90,80]])

fig = go.Figure()

fig.add_trace(go.Carpet(
    a = [0, 1, 2, 0, 1, 2, 0, 1, 2],
    b = [0, 0, 0, 1, 1, 1, 2, 2, 2],
    x = x.flatten(),
    y = y.flatten(),
    aaxis = dict(
        showticklabels = "none",
        showgrid = False,
    ),
    baxis = dict(
        showticklabels = "none",
        showgrid = False,
    )
))

fig.add_trace(go.Contourcarpet(
    a = [0, 1, 2, 0, 1, 2, 0, 1, 2],
    b = [0, 0, 0, 1, 1, 1, 2, 2, 2],
    z = z.flatten(),
    contours = dict(
        start = 80,
        end = 100,
        size = 1
    )
))

fig.write_html('test.html', auto_open=True)

在此处输入图像描述


推荐阅读