Search code examples
matplotlibplotlyplotly-python

create a cartesian 2D plane coordinate system using plotly


This creates the graph that I'm talking about using matplotlib:

import matplotlib.pyplot as plt
import numpy as np

xmin, xmax, ymin, ymax = -9, 9, -9, 9
fig, ax = plt.subplots(figsize=(20, 20))

ax.set(xlim=(xmin - 1, xmax + 1), ylim=(ymin - 1, ymax + 1), aspect='equal')

ax.spines['bottom'].set(position="zero", linewidth=2.5)
ax.spines['left'].set(position="zero", linewidth=2.5)
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

ax.text(10.15, 0, "x", fontdict=font, va="center")
ax.text(0, 10.15, "y", fontdict=font, ha="center")

x_ticks = np.arange(xmin, xmax)
y_ticks = np.arange(ymin, ymax)

ax.set_xticks(x_ticks[x_ticks != x_ticks])
ax.set_yticks(y_ticks[y_ticks != y_ticks])

ax.set_xticks(np.arange(xmin, xmax+1), minor=True)
ax.set_yticks(np.arange(ymin, ymax+1), minor=True)
ax.grid(which='both', color='grey', linewidth=1, linestyle='-', alpha=0.25)

plt.show()

Output: 2d cartesian plane as below enter image description here

Is it possible to get a similar result with plotly?


Solution

  • This is how it can be done in Plotly:

    import plotly.graph_objects as go
    
    axis_range = [-9,9]
    
    fig = go.Figure()
    
    fig.update_xaxes(range=axis_range,title = 'y', tickmode = 'linear',
                     showticklabels = False, side='top',gridcolor="rgb(224,224,224)")
    
    fig.update_yaxes(range=axis_range,title = 'x', tickmode = 'linear',
                     showticklabels = False, side='right', gridcolor="rgb(224,224,224)")
    
    fig.add_vline(x=0, line_width=3)
    fig.add_hline(y=0, line_width=3)
    
    
    
    fig.update_layout(plot_bgcolor='rgb(255,255,255)', height=800, width=800)
    
    fig.show()
    

    enter image description here

    The only drawback here is the label of x-axis cannot be rotated in Plotly as documented here.