How to plot in Python.

    In this post, I'll show how to visualize data in a plot by using matplotlib package in Python. You can find more information about the package in this link.

   We'll start loading the package.

import matplotlib.pyplot as plt

Plotting line chart 

    Below code shows hot generate sample data and visualize it in a line chart.

years = [1990, 1995, 2000, 2005, 2010, 2015]
c_sales = [0.2, 2, 5, 9, 18, 30]
b_sales = [1, 3.3, 4.2, 9, 14, 16]

plt.plot(years, c_sales, color="blue", marker="p", label="Ccc Inc.")
plt.plot(years, b_sales, color="green", marker="d", label="Bbb Inc.")
plt.ylabel("Sales trend in $ (mln)")
plt.legend()
plt.show() 



Below example shows how to plot multiple chart in single plot.
 
import random as rn

a = [2, 4, 5, 3, 6, 5, 7, 8, 9]
b = [i*1.2+rn.randint(1,5) for i in a]
c = [i/3+rn.randint(1,4) for i in a]
d = [i*1.2+rn.randint(1,6) for i in a]
x = range(len(a))

items = ["a", "b", "c", "d"] 
colors = ["red","blue", "green","orange"]

ig, ax = plt.subplots(4, figsize=(8, 14))
i = 0
for item in [a, b, c, d]:  
    ax[i].plot(x, item, label="y", color=colors[i])
    ax[i].set_title("List: "+str(items[i]))
    ax[i].legend()
    ax[i].grid(True)
    i+=1

plt.tight_layout()        
plt.show() 



 

No comments:

Post a Comment