3. Plotly API#

  • Easy to use

    • To create a viz, Single line of code, plt.plot(list)

import matplotlib.pyplot as plt
import numpy as np

3.1. Line Chart#

  • plot() creates line chart by default

    • Index as x axis

    • elements as y axis

plt.plot([0,1,2,3,4])
[<matplotlib.lines.Line2D at 0x7fc6c83dae20>]
../_images/44a29e0673197aae939d7a4e6759137f2988b0880324ef47a0b7dff82d14f67b.png

3.1.1. Important Points#

  • If we are coding outside of Jupyter, use plt.show()

  • If you want to supress the text message of viz, add semicolon in the end of plt.plot();

3.2. Bar chart#

  • Categorical vs Numerical

x=['a','b','c','d','e'] # 5 categorical values
y=[10,20,30,40,50] # 5 numerical values
plt.bar(x,y)
plt.show()

# Charts can be created in two lines of code
../_images/83920230da9def97acbdc53d4861c2a7733f6facc7184e7df30221af298e44bd.png

3.3. Customizations#

# Size of canvas
plt.figure(figsize=(8,4)) 

# Color
plt.bar(x,y,color='green') # Giving same color to all the bars
# plt.bar(x,y,color=['blue','black','yellow','green']) # Giving different color to all bars

# Labels
plt.xlabel('X axis')
plt.ylabel('Y axis')

# Title
plt.title('Bar chart')

# Showing grid
plt.grid()

plt.show()
../_images/1a01858fbac4fbd697d7321fa23de3d9e94ba0f6148a408a50f745cd5b205d07.png

3.3.1. Horizontal bar chart#

plt.barh(x,y)
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Bar chart')
plt.show()
../_images/527c28cd483904e65b59858f71599447a3cc2fa0edcf257f20346db03147ac9b.png

3.4. Scatter Plot#

x=np.random.rand(50)
y=np.random.rand(50)
  • Numerical data vs Numerical Data

plt.scatter(x,y)
<matplotlib.collections.PathCollection at 0x7fc6eb636730>
../_images/823cf82fcb44f29ebd4e06a884307bf216f9c2143fc961ac6fc28b798b7c309f.png

3.5. Customizations of plot#

  • Changing color,size

colors=np.random.rand(50)
sizes=(np.random.rand(50))*1000 # *1000 to get greater sizes
plt.scatter(x,y,c=colors,s=sizes,alpha=.5) # alpha for intensity

# Labels
plt.xlabel('X axis')
plt.ylabel('Y axis')

# Title
plt.title('Random chart')

# Size
plt.figure(figsize=(8,4))  

# Show
plt.show()
../_images/2f0d2c89f485d3b25297baecf37aaf3ac3082830a8700c464e4ae0666247e6d4.png
<Figure size 576x288 with 0 Axes>
  • Note: All of this needs to be defined in one cell only otherwise graph won’t show up

3.6. Plotting in coordinate system#

  • plot x points against y points

x=[10,20,30,40,50]
y=[640,700,80,190,1000]
plt.plot(x,y)
plt.show()
../_images/a77c1b143b363f375e022e70e6221cf5502f641c5e389c77880f3bd63e710f15.png

3.7. Histogram#

  • Intensity of repetations

x=[1,2,3,4,5,4,3,1,1,3,3,2,1,4,4,4,4]
plt.hist(x)
plt.show()
../_images/10cf77d5241a198894d686bf0dba91513bfd63e1674fca579ad39c5fe39f38eb.png