0% found this document useful (0 votes)
8 views

GRAPHS USING MATPLOTLIB

The document provides a comprehensive guide on creating various types of graphs using Matplotlib, including vertical and horizontal bar charts, pie charts, scatter plots, and box plots. It includes code snippets for each type of graph, explaining the use of different parameters and customization options. Additionally, it covers the plotting of mathematical functions such as sine, cosine, and tangent, along with examples of multiple box plots.

Uploaded by

rananavdeep65
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

GRAPHS USING MATPLOTLIB

The document provides a comprehensive guide on creating various types of graphs using Matplotlib, including vertical and horizontal bar charts, pie charts, scatter plots, and box plots. It includes code snippets for each type of graph, explaining the use of different parameters and customization options. Additionally, it covers the plotting of mathematical functions such as sine, cosine, and tangent, along with examples of multiple box plots.

Uploaded by

rananavdeep65
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

*GRAPHS USING MATPLOTLIB*

#there are two parameters for specifying points in the diagram i.e. x-axis and y-axis.
#here in the diagram the line appears bcz it is the by default function.

import matplotlib.pyplot as plt #now the pyplot package can be refered as plt

*VERTICAL BAR CHART*

import matplotlib.pyplot as plt


# Data for the bar chart
categories = ['Category 1', 'Category 2', 'Category 3', 'Category 4']
values = [25, 40, 15, 30]

# Create the bar chart


plt.bar(categories, values, color='lightblue')

# Add labels and title


plt.xlabel('Categories')#plt.xlabel is used to add a label to the x-axis of a plot
plt.ylabel('Values')#plt.ylabel is used to add a label to the y-axis of a plot
plt.title('Example Vertical Bar Chart')#plt.title is used to provide the title of the bar chart

# Display the chart


plt.show()#plt.show is used to display the created plot

*BAR CHART*

import matplotlib.pyplot as plt


subjects=['Hindi','English','Maths','Sanskrit']
marks=[42,45,35,25]
plt.bar(subjects,marks,color='lightblue',width=0.5,edgecolor='black')#plt.bar is used to create bar plots.
#width is used for determining the width of the bars.
#edgecolor is used for give the outline of the edges
#color is used to provide the color of the bars
plt.xlabel('marks')#plt.xlabel is used to add a label to the x-axis of a plot
#plt.ylabel is used to add a label to the y-axis of a plot
#plt.title is used to provide the title of the bar chart
plt.ylabel('subjects')
plt.title('marks of the students')
plt.show()
*HORIZONTAL BAR CHART*

import matplotlib.pyplot as plt


Fruits=['Apples','Bananas','Litchi','Mango','Pineapple']
Sales=[350,450,300,500,200]
plt.barh(Fruits,Sales,color='white',height=0.5,edgecolor='black')#plt.barh is used to make a horizontal bar plot.
plt.xlabel('Fruits')#plt.xlabel is used to add a label to the x-axis of a plot
#plt.ylabel is used to add a label to the y-axis of a plot
#plt.title is used to provide the title of the bar chart
plt.ylabel('Sales')
plt.title('Sales of the Fruits')
plt.show()

*MULTIPLE BAR CHART*

import matplotlib.pyplot as plt


w=0.2 #it is used to provide the width of the bars.
fig=plt.subplots(figsize=(10,6))#plt.subplots is used to easily plot multiple graphs in a single figure.
#figsize provides the size of the figures
IT=[12,30,10,8,22]
CSE=[25,35,45,50,55]
ECE=[10,12,15,20,30]
import numpy as np
br1=np.arange(len(IT))#np.arange is used to create arrays with evenly spaced values within a given interval.
#len() returns the number of items in an object.
br2=[x+w for x in br1]
br3=[x+w for x in br2]
plt.bar(br1,IT,width=w,color='lightblue')#plt.bar is used to create bars.
plt.bar(br2,CSE,width=w,color='yellow')
plt.bar(br3,ECE,width=w,color='lightgreen')
plt.xticks([r+w for r in range(len(IT))],['2015','2016','2017','2018','2019'])#plt.xticks is used to get or set the x
plt.show()

*PIE CHART USING FIGSIZE,SHADOW,WEDGEPROPS,AUTOPCT,TEXTPROPS AND EXPLODE*

import matplotlib.pyplot as plt


import numpy as np
gender=['Males','Females']
data=[75,25]
fig=plt.figure(figsize=(4,4))
plt.pie(data,labels=gender,colors=['pink','lightblue'],shadow=True,wedgeprops={'linewidth':1,'edgecolor':'black'},aut
explode=(0.2,0.4),textprops={'fontfamily':'serif','fontsize':12})
#plt.pie is used to create pie charts.
#shadow is used to create a fancy pie chart ready for presentations.
#wedgeprops is used to customize the appearance of each wedge (or slice) within the chart.
#autopct allows us to display the percent value using string formatting
#tells us about the wedges i.e. those lines which define the other lines
#what should be the format for what values should be written inside the chart-autopct, we took 1.1 bcz we want only 1
#explode is used to make parts of a pie chart stand out without changing the underlying data.
#textprops is used for defining the chracteristics of text.
plt.show()

#MORE EXAMPLES
Cars=['Audi','BMW','Ford','Tesla','Jaguar','Mercedes']
Sold=[23,17,35,29,12,41]
fig=plt.figure(figsize=(4,4))
plt.pie(Sold,labels=Cars,colors=['lightblue','pink','white','yellow','lightgreen','orange'],wedgeprops={'linewidth'
explode=(0.1,0.1,0.1,0.1,0.1,0.1),textprops={'fontfamily':'serif','fontsize':12})
plt.show()
*SCATTER PLOTS*

x=[2,3,4,5,6]
y=[4,6,8,10,12]
y2=[-2,-3,-4,-5,-6]
plt.scatter(x,y,color='orange',marker="*",label='data1')#plt.scatter is used to create scatter plots.
plt.scatter(x,y2,color='blue',marker="o",label='data2')
plt.legend()#plt.legend gives meaning to a visualization, assign meaning to the various plot elements.
plt.xlabel("x")#plt.xlabel is used to add a label to the x-axis of a plot
plt.ylabel("y")#plt.ylabel is used to add a label to the y-axis of a plot
plt.title("Numbers")#plt.title is used to add a title to the charts/plots
plt.show()#plt.show is used to display the created charts/plots

*GRAPH OF SIN X*

x=np.linspace(0,2*np.pi,100)#linspace() allows you to specify the total number of points you want in the array
y=np.sin(x)#np.sin(x) helps to find sine value of the angle in degree and radian
plt.plot(x,y,label='sinx',color='red')#plt.plot is used for creating line plots
plt.xlabel('x')#plt.xlabel is used to add a label to the x-axis of the plot
plt.ylabel('y')#plt.ylabel is used to add a label to the y-axis of the plot
plt.title('graph of sinx')#plt.title is used to give the title of the plot
plt.legend ()#plt.legend gives meaning to a visualization, assign meaning to the various plot elements
plt.show()#plt.show is used t display the created plots/charts
*GRAPH OF COS X*

x=np.linspace(0,2*np.pi,100)#linspace() allows you to specify the total number of points you want in the array
y=np.cos(x)#np.cos(x) helps to compute the cosine of an angle x given in radians.
plt.plot(x,y,label='cosx',color='blue')#plt.plot is used for creating line plots
#label is used for labelling the graph.
#plt.xlabel is used to add a label to the x-axis of the plot
#plt.ylabel is used to add a label to the y-axis of the plot
#plt.title is used to give the title of the plot
#plt.legend gives meaning to a visualization, assign meaning to the various plot elements
#plt.show is used t display the created plots/charts
plt.xlabel('x')
plt.ylabel('y')
plt.title('graph of cosx')
plt.legend()
plt.show()

*GRAPH OF X*X

x=np.linspace(0,20,100)#linspace() allows you to specify the total number of points you want in the array
y=x*x
plt.plot(x,y,label='x*x',color='green')
plt.xlabel('x')
plt.ylabel('y')
plt.title('graph of x*x')
plt.legend()
plt.show()
#plt.plot is used for creating line plots
#label is used for labelling the graph.
#plt.xlabel is used to add a label to the x-axis of the plot
#plt.ylabel is used to add a label to the y-axis of the plot
#plt.title is used to give the title of the plot
#plt.legend gives meaning to a visualization, assign meaning to the various plot elements
#plt.show is used t display the created plots/charts

*GRAPH OF TAN X*

x=np.linspace(0,2*np.pi,100)#linspace() allows you to specify the total number of points you want in the array
y=np.tan(x)#np.tan(x) helps user to calculate trigonometric tangent for all x(being the array elements)
plt.plot(x,y,label='tanx',color='orange')
plt.xlabel('x')
plt.ylabel('y')
plt.title('graph of tanx')
plt.legend()
plt.show()
#plt.plot is used for creating line plots
#label is used for labelling the graph.
#plt.xlabel is used to add a label to the x-axis of the plot
#plt.ylabel is used to add a label to the y-axis of the plot
#plt.title is used to give the title of the plot
#plt.legend gives meaning to a visualization, assign meaning to the various plot elements
#plt.show is used t display the created plots/charts

*VERTICAL BOX PLOT*

import matplotlib.pyplot as plt


# Sample data
data = [7, 15, 13, 18, 21, 15, 12, 16, 14, 19]
# Create figure and axis for box plot
plt.figure(figsize=(8, 6))#provides the size of the figure
# Create box plot with customizations
box = plt.boxplot(data, patch_artist=True, widths=0.3)#plt.boxplot is used to create box plots
#PATCH_ARTIST fills the boxplot with colors, we can set different colors to different boxes
#width provides the width of the boxes
# Customize the colors and edges
box['boxes'][0].set_facecolor('lightblue') #it gives the facecolor lightblue
box['boxes'][0].set_edgecolor('black') # set.edglecolor gives black edge for the box
box['medians'][0].set_color('darkblue') # set_color gives dark blue median line
# Add title and labels
plt.title("Custom Box Plot", fontsize=14)
plt.ylabel("Values", fontsize=12)
# Show plot
plt.tight_layout()#it ensure that your plots are clear and easy to interpret
plt.show()#it displays that has been created

*HORIZONTAL BOX PLOT*

import matplotlib.pyplot as plt

# Sample data
data = [8, 16, 12, 19, 22, 17, 13, 14, 11, 20]

# Create figure
plt.figure(figsize=(8, 5))

# Create horizontal box plot with custom styling


box = plt.boxplot(data, patch_artist=True, vert=False, widths=0.5)#vert=false is used to draw horizontal plot
#plt.boxplot is used to create box plots
#PATCH_ARTIST fills the boxplot with colors, we can set different colors to different boxes
#width provides the width of the boxes
# Customize the colors and edges

# Style the box


box['boxes'][0].set_facecolor('pink') #it gives the face color pink
# set.edglecolor gives black edge for the box
# set_color gives dark blue median line
box['boxes'][0].set_edgecolor('black')
box['medians'][0].set_color('darkblue')

# Set title and axis labels


plt.title("Horizontal Box Plot", fontsize=14)
plt.xlabel("Values", fontsize=12)

# Show the plot


plt.tight_layout()
plt.show()
#it ensure that your plots are clear and easy to interpret
#it displays that has been created

*MUTIPLE BOX PLOT*

# Importing libraries
import matplotlib.pyplot as plt

# Sample data
data_dict = {
'Group A': [23, 45, 56, 67, 34, 89, 45],
'Group B': [34, 56, 78, 12, 45, 67, 89],
'Group C': [13, 24, 35, 46, 57, 68, 79]
}

# Creating the boxplot with color,boxprops,medianprops,whiskerprops


plt.boxplot(data_dict.values(), labels=data_dict.keys(),patch_artist=True,
boxprops=dict(facecolor='lightblue', color='darkblue'),
medianprops=dict(color='red'),
whiskerprops=dict(color='green'))
plt.title("Customized Boxplots")
plt.xlabel("Groups")
plt.ylabel("Value Range")
plt.show()
#boxprops:Allows you to customize the appearance of the central box
#whiskerprops:Controls the appearance of the whiskers (lines extending from the box),
#enabling you to change their color,linewidth, linestyle, and other properties
#medianprops:Controls the appearance of the median line within the box, enabling you to adjust its color, linewidth,
#patch_artist:A boolean argument that determines whether the boxplot's box should be filled with a color (True) or
#if it should only show the outline (False)
Loading [MathJax]/jax/output/CommonHTML/fonts/TeX/fontdata.js

You might also like