Im trying to make a python script that will allow me to insert a string of coordinates and have them plotted on a graph/plane, I have it set so if you use an incorrect format eg: (x,y), (x,y ,(x,y) that it will say incorrect format becaue of the missing parenthisis however, whenever I try to get it to allow decimal points it either keeps flagging everything or just doesnt connect them via lines. I have it so it will connect the points via lines in the order they were listed if a comma is used to seperate the different coordinates eg: (x,y), (x,y) however if a period is used in between points it won’t connect a line between those specific points eg: (x,y). (x,y) this allows me to make things that look like a completed connect the dots, however that breaks a lot of the time when trying to allow decimal points as it gets confused between whats a decimal point and whats a line seperator. I know that decimals need to be declaired as a ‘float’ unlike whole numbers, and my code doesnt do that and ive yet to figure out how to do so. Does anyone know how I can get my code to allow decimals whilst not breaking the other stuff? The code I have so far has working lines, and line seperation via the periods, however it doesnt accept decimal numbers:
# Import necessary libraries
import plotly.graph_objects as go # Library for creating interactive plots
import ipywidgets as widgets # Library for creating interactive widgets in Jupyter notebooks
from IPython.display import display, clear_output # Function to clear previous output in Jupyter notebooks
# Function to safely convert string representation of a point to a tuple
def parse_point(point_str):
try:
point_str = point_str.strip() # Remove leading and trailing whitespace
if not point_str.startswith("(") or not point_str.endswith(")"):
raise ValueError("Point must be enclosed in parentheses.")
point_str = point_str[1:-1] # Remove parentheses
x_str, y_str = point_str.split(",") # Split by comma
x = float(x_str.strip()) # Convert x-coordinate to float
y = float(y_str.strip()) # Convert y-coordinate to float
return x, y
except Exception as e:
raise ValueError(f"Invalid point format: {point_str}")
# Function to plot points on a Plane
def plot_points(points):
try:
# Split the input string based on periods to separate segments
segments = points.split('.')
all_points = []
for segment in segments:
# Remove any extra spaces
segment = segment.strip()
# Check if segment is empty
if not segment:
continue
# Split segment by comma to separate points
segment_points = segment.split(',')
# Convert coordinates to tuples
for point_str in segment_points:
all_points.append(parse_point(point_str))
# Extract x and y coordinates from all points
x_values = [point[0] for point in all_points]
y_values = [point[1] for point in all_points]
# Create a new plotly figure
fig = go.Figure()
# Add a scatter trace for all points
fig.add_trace(go.Scatter(x=x_values, y=y_values, mode='markers', name='Points'))
# Add traces for the lines connecting the points in each segment
for i in range(0, len(all_points)-1, 2):
fig.add_trace(go.Scatter(x=[all_points[i][0], all_points[i+1][0]],
y=[all_points[i][1], all_points[i+1][1]],
mode='lines+markers', line=dict(color='blue', width=2), name=''))
# Update layout of the plot
fig.update_layout(title='Points on Cartesian Plane',
xaxis_title='X-Axis', yaxis_title='Y-Axis', # Set axis titles
xaxis=dict(range=[-99, 99], autorange=False), # Set x-axis range and disable autorange
yaxis=dict(range=[-99, 99], autorange=False, showticklabels=False), # Set y-axis range and disable tick labels
showlegend=False, # Hide legend
width=600, height=575) # Set width and height to make it square
fig.show() # Show the plot
except (SyntaxError, ValueError) as e:
# Display error message if there's a syntax error in the input format
error_message.value = f"Incorrect format. {e}"
display(error_message)
display(points_input)
display(plot_button)
# User input box for points
points_input = widgets.Text(description="Points:")
# Error message display
error_message = widgets.HTML(value="", layout=widgets.Layout(color='red'))
# Plot button
plot_button = widgets.Button(description="Plot")
def on_plot_button_clicked(b):
clear_output() # Clear previous output
error_message.value = "" # Clear previous error message
plot_points(points_input.value)
plot_button.on_click(on_plot_button_clicked)
# Display the input box and plot button initially
display(points_input)
display(plot_button)
Ashton Raymer is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.