How to create a graph in Python

For creating graphs in python we need to know about ‘matplotlib’ library.

 Matplotlib:- Matplotlib is a python package used for creating 2D graphics, or it

represents your data in the graphical form.


Types of the plot:-

 Bar graph

 Histogram

 Scatter plot

 Pie plot

 Area or Stack plot

Here is the basic code for the simplest graph.:-

(1)

from matplotlib import pyplot as plt                # This will import matplotlib module

plt.plot([X-Coordinate], [Y-Coordinate])         # plot()function will plot the graph

plt.show()                                                         # This function will show the graph


Example:-

from matplotlib import pyplot as plt

plt.plot([1, 2, 3, 1, 1], [4, 5, 1, 1, 4])

plt.show()


Output:-

(2) Bar graph

Keywords:- 
  1. label = “Legends of the graph”
  2. color = “Color for the graph”
  3. linewidth = Width of the line

Example:-
from matplotlib import pyplot as plt

plt.bar([1,3,5,7,9],[5,2,7,8,2], label = "PC Gamers")
plt.bar([2,4,6,8,10],[8,6,2,5,6], label = "Mobile Gamers", color = "g")

plt.legend()                             # This function will print the legends
plt.xlabel("Months")
plt.ylabel("No. of gamers")
plt.title("Graph of gamers")   # This function will print the heading of the graph

plt.show()

Output:-


(3) Stack or Area plot


from matplotlib import pyplot as plt

# Variables for graph

Days = [1,2,3,4,5]
Sleeping = [7,8,6,11,17]
Eating = [2,3,4,3,2]
Working = [7,8,7,2,2]
Playing = [8,5,7,8,13]

plt.plot([],color="m", label="Sleeping",linewidth=5)
plt.plot([],color="c", label="Eating",linewidth=5)
plt.plot([], color="r", label="Working",linewidth=5)
plt.plot([],color="k", label="Playing",linewidth=5)
plt.stackplot(Days, Sleeping, Eating, Working, Playing, colors=['m','c','r','k'])

plt.xlabel('x')
plt.ylabel('y')
plt.title('Area Plot')
plt.legend()
plt.show()


Output:-



(4) Pie Chart

Keywords:

(a) Startangle:- Start angle of the pie chart

(b) Explode:- This will took a pie away from the chart

(c) Autopact:- This will overlay the percentage in the graph


Example



Slices = [85,87,91,84,81]

Subjects = ["English","Sanskrit","Maths","Science", "Social Science"]

Colours = ["c","y","c","r","g"]

plt.pie(Slices,

labels= Subjects,

colors= Colours,

startangle= 90,

shadow= True, # Optional for adding shadow to the graph

explode= (0,0,0.1,0,0),

autopct= '%1.1f%%',

)

plt.title('Pie Plot')

plt.show()





Output:-



(5) Scatter Plot:-



x = [1,2,3,4,5,6,7,8]

y = [5,2,4,2,1,4,5,2]



plt.scatter(x,y, label="Skitscat", color="k")

plt.xlabel("X")

plt.ylabel("Y")

plt.title("Scatterplot")

plt.legend()

plt.show()

Output:




By:- Tathagat Chavada




Next Post Previous Post
No Comment
Add Comment
comment url