Write Python code to display graph of function in console. Use ANSI escape codes, if…
- User
Write Python code to display graph of function in console. Use ANSI escape codes, if needed. Function: y = 3x
- Assistant
Write Python code to display graph of function in console. Use ANSI escape codes, if needed. Function: y = 3x
Sure! Below is a Python script that plots the linear function ( y = 3x ) directly in the console using ASCII characters and ANSI escape codes for coloring. The script creates a simple Cartesian plane with axes and plots the line accordingly.
| and - respectively, with the origin marked by +.*.import sys
# ANSI escape codes for coloring
RESET = "\033[0m"
COLOR_AXES = "\033[94m" # Blue
COLOR_LINE = "\033[91m" # Red
def plot_function(func, x_range, y_range, width=80, height=24):
"""
Plots a mathematical function on the console.
Parameters:
- func: The function to plot. It should take a single float argument and return a float.
- x_range: Tuple (x_min, x_max) defining the range of x values.
- y_range: Tuple (y_min, y_max) defining the range of y values.
- width: The width of the plot in characters.
- height: The height of the plot in characters.
"""
x_min, x_max = x_range
y_min, y_max = y_range
# Create a 2D grid initialized with spaces
grid = [[' ' for _ in range(width)] for _ in range(height)]
# Calculate scaling factors
x_scale = (x_max - x_min) / (width - 1)
y_scale = (y_max - y_min) / (height - 1)
# Determine the position of the axes
try:
y_zero = int(round((0 - y_min) / y_scale))
except ZeroDivisionError:
y_zero = height // 2
try:
x_zero = int(round((0 - x_min) / x_scale))
except ZeroDivisionError:
x_zero = width // 2
# Plot the axes
for i in range(height):
if i == y_zero:
for j in range(width):
grid[i][j] = f"{COLOR_AXES}-" # X-axis
if x_zero >=0 and x_zero < width:
grid[i][x_zero] = f"{COLOR_AXES}|"{RESET} # Y-axis
# Mark the origin
if 0 >= x_min and 0 <= x_max and 0 >= y_min and 0 <= y_max:
if 0 <= y_zero < height and 0 <= x_zero < width:
grid[y_zero][x_zero] = f"{COLOR_AXES}+{RESET}"
# Plot the function
for j in range(width):
# Corresponding x value
x = x_min + j * x_scale
y = func(x)
# Corresponding row in grid
i = height - 1 - int(round((y - y_min) / y_scale))
if 0 <= i < height:
# Avoid overwriting the origin
if grid[i][j] == f"{COLOR_AXES}-" or grid[i][j] == f"{COLOR_AXES}|":
grid[i][j] = f"{COLOR_LINE}*{RESET}"
else:
grid[i][j] = f"{COLOR_LINE}*{RESET}"
# Print the grid
for row in grid:
print("".join(row))
def main():
# Define the function y = 3x
def func(x):
return 3 * x
# Define the range for x and y
x_range = (-10, 10)
y_range = (-30, 30)
# Optionally, you can adjust width and height based on your console size
plot_function(func, x_range, y_range, width=80, height=24)
if __name__ == "__main__":
main()
ANSI Colors: The script defines ANSI escape codes for coloring the axes (COLOR_AXES) in blue and the function line (COLOR_LINE) in red. The RESET code resets the console color back to default after coloring each character.
Scaling: The function plot_function calculates the scaling factors based on the desired width and height of the plot and the range of x and y values. This ensures that the graph fits within the specified console size.
Axes Positioning: The script determines where to place the X and Y axes based on where zero falls within the scaled grid. It marks the origin with a +.
Plotting the Function: For each column (representing an x-value), the script computes the corresponding y-value using the provided function. It then maps this y-value to the appropriate row in the grid and plots a *. If the point coincides with an axis, it overwrites the axis character.
Printing the Grid: Finally, the grid is printed row by row, resulting in a visual representation of the function in the console.
When you run the script, you should see a graph similar to the following (colors will appear in the console):
*
*
*
*
*
*
*
*
*
*
-----------+************************************************************
*
*
*
*
*
*
*
*
*
*
Each * represents a point on the line ( y = 3x ), the + marks the origin, and the axes are colored differently for clarity.
Adjusting Scale: Depending on your console size, you might want to adjust the width and height parameters in the plot_function call to better fit the graph.
Color Support: Ensure your console or terminal supports ANSI escape codes to see the colored output. Most modern terminals do, but some older ones might not.
Function Modification: You can modify the func(x) definition to plot different functions as needed.
I hope this helps you visualize the function ( y = 3x ) directly in your console!
Not yet included in a published release.