How to plot a graph in Python
To plot a graph in Python, you’ll typically use a library such as Matplotlib. It is probably one of the most widely used and versatile libraries in terms of visualization. Here’s the step-by-step process to plot a simple graph:
Step 1: Install Matplotlib
Before you begin using Matplotlib, make sure you have the library installed on your machine; Matplotlib is a library that does not come preinstalled with Python. You can install it by using this code in your terminal or command prompt:
pip install matplotlib
Once installed, Matplotlib allows you to create a wide range of plots like line graphs, bar charts, scatter plots, histograms, and more.
Step 2: Import Matplotlib
You must import the library in your Python script or notebook to use the functionalities of it.
The most frequently used submodule of Matplotlib is pyplot
, which offers a high-level interface to make plots. The convention is:
import matplotlib.pyplot as plt
plt
is an alias (nickname) forpyplot
. It’s widely used to save typing and improve readability.
Step 3: Preparing Data
Before plotting a graph, you need data. Data is typically stored as lists, NumPy arrays, or pandas DataFrames.
Example:
x = [1, 2, 3, 4, 5] # Values for the x-axis
y = [2, 4, 6, 8, 10] # Values for the y-axis
Here:
x
represents the horizontal axis (independent variable).y
represents the vertical axis (dependent variable).
Step 4: Plotting the Graph
The basic command to create a line graph in Matplotlib is plt.plot(x, y).
Explanation:
plt.plot(x, y)
: Plots the values ofx
againsty
.- By default, the line is continuous, blue, and unmarked.
Adding Labels and Titles
You should always label your axes and give the plot a title for better understanding.
Example:
plt.xlabel('X-axis Label') # Label for the x-axis
plt.ylabel('Y-axis Label') # Label for the y-axis
plt.title('Simple Line Graph') # Title of the graph
Displaying the Graph
Finally, you use the plt.show()
function to render the graph and display it on the screen.
Complete Code:
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y) # Create the graph
plt.xlabel('X-axis') # Add x-axis label
plt.ylabel('Y-axis') # Add y-axis label
plt.title('Line Graph') # Add graph title
plt.show() # Display the graph
Step 5: Customizing the Graph
Customization is key to creating more informative and visually appealing graphs. Below are some ways you can customize your graph.
1. Adding Grid Lines
Use plt.grid()
to add grid lines for better readability.
plt.grid(True)
2. Changing Line Style, Color, and Marker
Matplotlib offers the possibility to change the appearance of the plot line.
- Line Style: Use
linestyle
to change the appearance of the line:- Solid (default):
linestyle='-'
- Dashed:
linestyle='--'
- Dotted:
linestyle=':'
- Solid (default):
- Line Color: Use
color
to change the color:- Examples:
'red'
,'blue'
,'green'
- Examples:
- Markers: Add markers to highlight data points:
- Examples:
'o'
(circle),'^'
(triangle),'s'
(square)
- Examples:
Example:
plt.plot(x, y, linestyle='--', color='red', marker='o')
3. Adding a Legend
A legend describes the data in the graph. Use label
to define a legend and plt.legend()
to display it.
Example:
plt.plot(x, y, label='Line 1')
plt.legend()
4. Setting Axis Limits
You can control the range of the axes using plt.xlim()
and plt.ylim()
.
Example:
plt.xlim(0, 6) # X-axis range: 0 to 6
plt.ylim(0, 12) # Y-axis range: 0 to 12
Step 6: Other Types of Graphs
Here are examples of different types of graphs you can create using Matplotlib:
1. Bar Chart
x = ['A', 'B', 'C']
y = [5, 7, 3]
plt.bar(x, y, color='purple')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Bar Chart')
plt.show()
2. Scatter Plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.scatter(x, y, color='green', marker='x')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
plt.title('Scatter Plot')
plt.show()
3. Histogram
A histogram is useful for visualizing the distribution of data.
data = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
plt.hist(data, bins=4, color='blue', edgecolor='black')
plt.xlabel('Bins')
plt.ylabel('Frequency')
plt.title('Histogram')
plt.show()
4. Pie Chart
A pie chart represents proportions.
labels = ['A', 'B', 'C']
sizes = [30, 40, 30]
plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90)
plt.title('Pie Chart')
plt.show()
Step 7: Saving the Graph
You can save the graph as an image file using plt.savefig()
.
Example:
plt.plot(x, y)
plt.savefig('plot.png') # Save as PNG
You can also specify the file format (.jpg
, .pdf
, .svg
, etc.) by changing the file extension.