how to plot a graph in python

Python has several libraries for data visualization. The most commonly used library is Matplotlib. Matplotlib is a 2D plotting library that helps in creating static, animated, and interactive visualizations in Python. To plot a graph using Matplotlib, follow the below steps:

  1. Import the required packages:

    main.py
    import matplotlib.pyplot as plt
    
    32 chars
    2 lines
  2. Prepare data for the graph:

    main.py
    x = [1, 2, 3, 4, 5]
    y = [2, 4, 6, 8, 10]
    
    41 chars
    3 lines
  3. Plot the data:

    main.py
    plt.plot(x, y)
    
    15 chars
    2 lines
  4. Add labels and title to the graph:

    main.py
    plt.xlabel("X-axis label")
    plt.ylabel("Y-axis label")
    plt.title("Title of the graph")
    
    86 chars
    4 lines
  5. Show the graph:

    main.py
    plt.show()
    
    11 chars
    2 lines

Here is the complete code:

main.py
import matplotlib.pyplot as plt

# Prepare data
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]

# Plot the data
plt.plot(x, y)

# Add labels and title
plt.xlabel("X-axis label")
plt.ylabel("Y-axis label")
plt.title("Title of the graph")

# Show the graph
plt.show()
260 chars
17 lines

This will create a simple line graph with the given data. You can customize the graph by using different types of plots like a scatter plot, bar plot, etc., and by tweaking the styling options.

gistlibby LogSnag