[CnC01] Basic Plotting Using Python
In our recent Code n Coffee session on August 17th, we explored the powerful plotting capabilities of matplotlib
, a popular plotting library in Python. This post will walk you through the functions and concepts we covered during the session.
Setting Up the Environment
To start with, we imported the necessary libraries:
import matplotlib.pyplot as plt
import numpy as np
from pandas import read_csv
matplotlib.pyplot
: The main plotting module in Matplotlib.numpy
: A library for numerical operations in Python, often used for handling arrays.pandas
: Used here to read the CSV data files containing our data.
We also set up the plotting environment by reading in the data from two CSV files:
data1 = read_csv('/content/line_reg1.csv')
data2 = read_csv('/content/line_reg2.csv')
x = data1['vi']
y = data1['vo']
x2 = data2['vi']
y2 = data2['vo']
read_csv
: A function from Pandas to load data from a CSV file into a DataFrame.x
,y
,x2
,y2
are arrays containing the data points for plotting.
Plotting the Data
We then plotted the data using plt.plot()
:
plt.plot(x, y, '--o', label='data1')
plt.plot(x2, y2, '-*', label='data2')
plt.xlabel("$V_i$")
plt.ylabel("$V_o$")
plt.legend()
plt.show()
plt.plot()
: This function plots the data points on a 2D graph. The first argument is the x-axis data, and the second is the y-axis data.- The style
--o
indicates a dashed line with circle markers fordata1
. - The style
-*
indicates a solid line with star markers fordata2
.
- The style
plt.xlabel()
andplt.ylabel()
: These functions label the x and y axes. We used LaTeX syntax ($...$
) to include mathematical symbols in the labels.plt.legend()
: Adds a legend to differentiate between the plotted data.plt.show()
: Displays the plot.
Fitting a Polynomial to the Data
Next, we demonstrated how to fit a polynomial to the data and plot the best-fit curve:
fit = np.polyfit(x2, y2, 3)
print(fit)
x_fit = np.linspace(6, 18, 100)
y_fit = np.polyval(fit, x_fit)
plt.plot(x2, y2, 'o', label="actual data")
plt.plot(x_fit, y_fit, '--', label="Best fit")
plt.legend()
plt.show()
np.polyfit(x, y, degree)
: This function fits a polynomial of the specified degree (3 in this case) to the data.np.linspace(start, stop, num)
: Generatesnum
evenly spaced points betweenstart
andstop
. We used this to create a smooth curve for the best-fit line.np.polyval(fit, x_fit)
: Evaluates the polynomialfit
at each point inx_fit
to produce the correspondingy
values.- The second
plt.plot()
command is used to plot both the actual data and the fitted polynomial curve.
Conclusion
This session gave us a strong foundation in using matplotlib
for data visualization. We learned how to:
- Plot basic data with different styles.
- Label axes and add legends.
- Fit a polynomial to data and visualize the fit.
Feel free to experiment with different data and plotting styles to further enhance your visualization skills!