Basic 2D-Plotting using Python : Matplotlib introduction

Hi Guys, 

We are going to learn how to generate simple 2D-plot using Python by reading some data from input file. We will go to much more complex plots later. We are going to use matplotlib library to achieve that. If you don't have library yet, check out my prerequisite list here. Here we go :

import numpy as np
import matplotlib.pyplot as plt

#defining lists

x=[]
y=[]

#opening data file in reading mode

with open ("data.dat","r") as f:

    for line in f: # reading data in lines
        row=line.split() # splitting lines to separated columns
        x.append(float(row[0])) # appending columns in arrays
        y.append(float(row[1]))

#conversion of lists in numpy arrays

x=np.asarray(x)
y=np.asarray(y)

# plotting data using matplotlib
# plt.plot : option1, option2 (x,y) 
# There are many customizations available. Check matplotlib website for more details 
# few important ones are 
# lw or linewidth, linestyle or ls, color, label, marker, markersize or ms and markeredgecolor, markerfacecolor

plt.plot(x,y, lw=1, ls='--', color='r', marker='^', markersize=10, markerfacecolor='k', label='plot1' )

# you can plot different data on the same plot simply by calling plot again and again.

plt.plot(2*x, 2*y, lw=1, ls= '-', color='k', marker='o', markersize=10, markerfacecolor='r', label='plot2')

#labeling axes and plot

plt.xlabel("X axis")
plt.ylabel("Y axis")
plt.title("This is a test plot")

# to show the plot and legend 
plt.legend()
plt.show()

Input :
1  3
2  4
5  7
6  4
8  5
1  3
1  5
1  4
output :



No comments:

Post a Comment