是否有与matplotlib pcolormesh等效的plotly?

2024-06-09 08:30:44 发布

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

我是编程和Python的新手。我正在研究一些教科书中的天线方向图,有一个叫做“正弦空间”的东西,天线方向图投影到x-y平面。生成的图案应包含在一个单位圆内)。当我使用matplotlib.pcolormesh时,我能够获得预期的模式。但我不知道如何让它有计划地工作

我试着用一本笔记本来说明我的问题。使用matplotlib.pcolormesh,您可以看到我得到了预期的绘图。我故意不包括实际的天线方向图计算,因为它们太长,不需要说明这个问题

# Import libraries
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

# Setup Sinespace
## - define theta and phi
theta = np.linspace(0, np.pi/2, 100)
phi = np.linspace(0, 2*np.pi, 100)

## - reshape theta and phi
thetaReshape = np.reshape(theta, (100, 1))
phiReshape = np.reshape(phi, (1, 100))

## - now when you multiply with thetaReshape and phiReshape you get a 100 x 100 array
u = np.sin(thetaReshape) * np.cos(phiReshape)
v = np.sin(thetaReshape) * np.sin(phiReshape)

# Generate a random array
Z = np.random.randn(100, 100)

# Setup and plot the figure
fig, ax = plt.subplots(1, 1)
ax.pcolormesh(u, v, Z)
ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_aspect(1)
fig.set_size_inches(4, 4)

Here's what I get with matplotlib.pcolormesh

上面的情节是我期望看到的。当我使用plotly时,我做了以下操作:

import plotly.graph_objects as go
fig = go.Figure(data=go.Heatmap(
                   z=Z,
                   x=u,
                   y=v
))
fig.show()

这导致下面的图毫无意义:

Here's what I get with Plotly

我对围棋也有同样的感觉

我真的很感谢你的帮助。谢谢


Tags: andimportmatplotlibasnpfigax方向
1条回答
网友
1楼 · 发布于 2024-06-09 08:30:44

我对天线物理不是很熟悉,所以我不确定您想要绘制什么,但我认为a成功地使用Plotly完成了一个工作示例,如下所示。我的建议是在极坐标系中绘图,而不是将坐标转换为笛卡尔空间

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Import libraries
import numpy as np
import plotly.graph_objs as go
from plotly.offline import plot
import plotly.express as px

# Setup Sinespace
# define theta and phi
theta = np.rad2deg(np.linspace(0, 2 * np.pi, 100))
phi = np.linspace(0, 1, 100)

theta, phi = np.meshgrid(theta, phi)

theta = theta.ravel()
phi = phi.ravel()
Z = np.random.randn(*theta.shape)

hovertemplate = ('my r: %{r}<br>'
                 'my theta: %{theta}<br>'
                 'my value: %{customdata[0]:.2f}<br>'
                 '<extra></extra>')

fig = go.Figure(
    go.Barpolar(
        r=phi,
        theta=theta,
        customdata=np.vstack((Z)),
        hovertemplate=hovertemplate,
        marker=dict(
            colorscale=px.colors.diverging.BrBG,
            showscale=True,
            color=Z,
        )
    )
)

fig.update_layout(
    title='My Plot',
    polar=dict(
        angularaxis=dict(tickvals=np.arange(0, 360, 10),
                         direction='clockwise'),
        radialaxis_tickvals=[],
    )
)

plot(fig)

此代码将生成以下绘图: enter image description here

这个答案是基于thisGitHub问题

相关问题 更多 >