How do I get plotly to show a grid of points?

Viewed 958

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. In this example I'm just making a 5 x 5 grid of points. I can do it successfully with Matplotlib, but not with Plotly. How do I get Plotly to make the grid of points like with Matplotlib? With Plotly it doesn't show all points. 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. 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')

1 Answers

The sample code below can be used to create the grid in Plotly:

Sample code:

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})

Output:

enter image description here

Comments:

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.

Regarding the issues you were having, this is because Plotly handles the meshgrid layout a bit differently from matplotlib. As such, I have used a very simple for loop and the zip() function in order to keep your existing dataset.

Related