[英]How do I get plotly to show a grid of points?
I'm kind of new to programming and I'm trying to use Python (Jupyter Notebook) to create a simple plot using Plotly which has a bunch of points in a grid configuration.我对编程有点陌生,我正在尝试使用 Python(Jupyter Notebook)使用 Plotly 创建一个简单的图,该图在网格配置中有一堆点。 In this example I'm just making a 5 x 5 grid of points.在这个例子中,我只是制作了一个 5 x 5 的点网格。 I can do it successfully with Matplotlib, but not with Plotly.我可以用 Matplotlib 成功地做到这一点,但不能用 Plotly。 How do I get Plotly to make the grid of points like with Matplotlib?我如何让 Plotly 像 Matplotlib 一样制作点网格? With Plotly it doesn't show all points.使用 Plotly,它不会显示所有点。 I want to use Plotly because it's more interactive and I'm working on something separately where I'm trying to put a simple point grid plot like this in a Plotly dashboard.我想使用 Plotly,因为它更具交互性,而且我正在单独处理一些事情,我试图在 Plotly 仪表板中放置一个像这样的简单点网格图。 Here's my code as it stands right now.这是我现在的代码。 I'd appreciate any help.我很感激任何帮助。 Thanks!谢谢!
# Import libraries
import numpy as np
import plotly.graph_objs as go
import matplotlib.pyplot as plt
%matplotlib inline
# Set up sample data
posX = [0, 1, 2, 3, 4]
posY = [-2, -1, 0, 1, 2]
posXX, posYY = np.meshgrid(posX, posY)
# Use Matplotlib
f, ax = plt.subplots()
ax.plot(posXX, posYY, 'o', ms=5)
ax.set_xlabel('X Position')
ax.set_ylabel('Y Position')
ax.set_title('Point Grid');
# Now use Plotly
fig = go.Figure()
fig.add_trace(go.Scatter(x = posXX, y = posYY, mode = 'markers'))
fig.update_layout(title = 'Point Grid',
xaxis_title = 'X Position',
yaxis_title = 'Y Position',
hovermode = 'x')
The sample code below can be used to create the grid in Plotly:下面的示例代码可用于在 Plotly 中创建网格:
from plotly.offline import iplot
colours = ['blue', 'orange', 'green', 'red', 'purple']
layout = {'title': 'Point Grid'}
traces = []
for x, y, c in zip(posXX.T, posYY.T, colours):
traces.append({'x': x,
'y': y,
'mode': 'markers',
'marker': {'color': c,
'size': 10},
'name': c})
layout['xaxis'] = {'title': 'X Position'}
layout['yaxis'] = {'title': 'Y Position'}
iplot({'data': traces, 'layout': layout})
I have intentionally used the lower-level Plotly code here, as (personally) I feel it provides a greater level of transparency as to what's going on under the surface of graph_objects
, and provides easier configuration.我在这里特意使用了较低级别的 Plotly 代码,因为(个人)我觉得它为graph_objects
表面下发生的事情提供了更高级别的透明度,并提供了更简单的配置。
Regarding the issues you were having, this is because Plotly handles the meshgrid
layout a bit differently from matplotlib
.关于您遇到的问题,这是因为 Plotly 处理meshgrid
布局与matplotlib
meshgrid
不同。 As such, I have used a very simple for loop and the zip()
function in order to keep your existing dataset.因此,我使用了一个非常简单的 for 循环和zip()
函数来保留您现有的数据集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.