<jupyter_start><jupyter_text>GRAPHS Plotting Graphs  To learn about and plot high quality, detailed graphs, we will be using Matplotlib, a Python library for data visualization. There is usually no need to install it separately because Anaconda has it installed by default. We will be drawing different types of graphs like line graph, bar graph, pie charts, etc. and adding styles, colours, legends, title, etc in these graphs.  PyplotTo start plotting graphs, we import the pyplot submodule from matplotlib. Pyplot is a collection of command style functions that make matplotlib work like MATLAB. Each pyplot function makes some change to a figure: e.g., creates a figure, creates a plotting area in a figure, plots some lines in a plotting area, decorates the plot with labels, etc.In order to plot a 2-D graph (say), we need to have a pair of coordinates: those of the x and y axes. If we declare our coordinates as arrays, the size of the x-coordinate array and y-coordinate array must be same. Matplotlib is convenient in that in order to plot the coordinates with, say a scatter plot, we simply have to write pyplot.scatter() and we can have the points plotted on a scatter plot. Note that this will plot the graph but won’t display it; we need to write pyplot.show() in order to display the graph.<jupyter_code>#Importing pyplot library 
import matplotlib.pyplot as plt
#Importing Numpy library
import numpy as np<jupyter_output><empty_output><jupyter_text>Matplotlib works with all sorts of data. If it were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally.If we wish to have the points linked and not scattered, we can use pyplot.plot() for the same. The advantage of these functions is that there are several properties and parameters we can tinker with in order to enhance our graph further. We can give it colours and even the pattern of the lines in between the points, for instance dashed or bold. You can make several plots like bar graphs, histograms etc. and also adjust scales – like setting a logarithmic scale etc. The plot() function accepts an arbitrary number of arguments.<jupyter_code>#plotting values on the graph
A = [7,84,53,44,69]
plt.plot(A)
plt.show()
#plotting graph with 2 inter-related variables (through some function)
X = [2,5,7,11]
Y = [13,22,37,30]
plt.plot(X,Y)
plt.show()<jupyter_output><empty_output><jupyter_text>ScatterIf we want to plot random data points without connecting them with lines, we can use scatter.<jupyter_code>X = np.array([1,3,4,5,7])
Y = np.array([4,1,9,7,2])
plt.scatter(X,Y)
plt.show()
# plotting a function with respect to given points. The 'ro' 
# parameter specifies two things: the 'r' specifies the color of 
# the points which is red, and the 'o' specifies the shape.
x = np.array([1,2,3,4,5])
y = x**4
plt.plot(x,y,'ro')
plt.show()<jupyter_output><empty_output><jupyter_text>Line graphWe can plot linearly related mathematical functions (y=mx+b) using pyplot.<jupyter_code>m = 10
b = 5
X = np.array([1,8,20,45])
Y = m*X + b
plt.plot(X,Y)
plt.show()
# Plotting function y = x^3

# X = np.array([-10,0,10])
X = np.array([-10,-9,-8,-7,-5,-4,-3,-2,-1,0,1,2,3,4,5,6,7,8,9,10])
print('X --> ',X)
# X = np.linspace(-15,15,100)
# This is another way of creating X array with numbers 100 linearly spaced numbers from -15 to 15
# You can uncomment it to see the plot.
Y = X**3
plt.plot(X,Y)
plt.show()
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
# we can plot multiple functions within one plot as well.
plt.plot(t, t**3, color = 'green', marker='^')
plt.show()<jupyter_output><empty_output><jupyter_text>Adding Styles in graphs * Colors * Markers* Line style* Line Width* Adding labels along axisNow that we know how to create basic plots, how do we customize them?You can change the colour of your plots by adding a ‘color’ parameter in the plot function definition (which can accept an arbitrary number of arguments, by the way). Adding a ‘marker’ parameter will shape your plot points – say circular, triangular etc. You need to give the character ‘o’ for a circular shape and ‘^’ for triangular.There are many, many other arguments that can be passed as well. For instance, the linewidth parameter adjusts the width of our plot line – how thick or thin you want it to be.Now how do we make our graph more descriptive? That is usually done by adding labels to the axes, a legend (scale) to the graph and so on.To give a label to the y-axis, use the ylabel function and give it the label name which you prefer, and similarly for the x-axis use the xlabel function. Note that these have to be defined before the show() function, or they won’t run.The title() function will be used to provide the title for the graph, and the legend() function will set the legend for the plot – but only after you specify the ‘label’ attribute in the plot() function definition.You can also set the axis length for both your axes by specifying the axis() function and giving it the start and end points for both axes, and also visualize your graph through a grid by using the grid() function. The advantage of using a grid is that the plotted points are easier to track and visualize.What if you want to add some text to your graph at some random place in it? The text() function comes in handy. You need to specify the coordinates where you want to add your text and the content you want to be displayed. You can also add the fontsize parameter to it to adjust the size of the text.The subplot function allows one to plot multiple subplots within one plot. You need to specify the sizes which will be occupied by it in the bigger plot. For example, subplot(2, 3, 3) and subplot(233) both create an Axes at the top right corner of the current figure, occupying half of the figure height and a third of the figure wLet's understand these step by step -<jupyter_code>N = 50
X = np.array([1,2,4,5])
Y = np.array([10,35,78,10])

#Color property can be used to change colours

plt.plot(X,Y,color = 'orange')
#We can use any color here in values

plt.show()
N = 50
X = np.array([1,2,4,5])
Y = np.array([10,35,78,10])

#Marker property can be used to change markers to any valid marker style like circle,diamond,triangle,etc.

plt.plot(X,Y,marker = 'o')
#We can use any color here in values

plt.show()<jupyter_output><empty_output><jupyter_text>We can use format strings to change colour, markers and line styles.fmt = '[color][marker][line]'All of these are optional. By default, we have blue solid line.<jupyter_code>N = 50
X = np.random.rand(N)
Y = np.random.rand(N)

plt.plot(X,Y,'ro')
# here, r is for red colour and o is for circle

# ro - is used for plotting red circles
# plt.plot(X,Y,'bo') - for blue circle
# plt.plot(X,Y,'r+') - red colour and + marker
# plt.plot(X,Y,'b--') - for blue dotted lines  
# plt.plot(X,Y,'o-')
# plt.plot(X,Y,'g--d') - green dotted line with diamond shape marker
# plt.plot(X,Y,'k^:') - black triangle_up markers connected by a dotted line

plt.show()
X = np.array([1,2,3,4])
Y = np.array([13,9,78,45])
plt.plot(X,Y,linewidth = 4.5)
#linewidth can take any float values
plt.show()
t = np.arange(0, 5, 0.2)
# t has evenly sampled values from 0 to 5 with 0.2 step value
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
# red dashes, blue squares and green triangles
# we can plot multiple equations on the same figure
plt.show()
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
# we can plot multiple functions within one plot as well.
plt.plot(t, t**3, color = 'green', marker='^')
plt.show()
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
colors = np.random.rand(N)
area = np.pi * (15 * np.random.rand(N))**2

# s - size of points, can be a single number or an array
# c - colour of the points
# alpha - transparency value of colours
plt.scatter(x, y, s=area, c=colors, alpha=0.5)
plt.show()<jupyter_output><empty_output><jupyter_text>Adding labels and title in graphs<jupyter_code>X = np.array([1,2,3,4])
Y = np.array([13,9,78,45])
plt.plot(X,Y)
plt.ylabel("Some random values")
plt.xlabel("Points")
# Adding x and y axis labels
plt.title("Plotting random values v/s data points")
# Adding title on the graphs
plt.show()<jupyter_output><empty_output><jupyter_text>LegendsWhile plotting lines on the graph, we can add legends for description about what information is shown or depicted with help of those plots.<jupyter_code>plt.plot([0.1, 0.2, 0.3, 0.4], [1, 2, 3, 4], label='first plot')
plt.plot([0.1, 0.2, 0.3, 0.4], [1, 4, 9, 16], label='second plot')
plt.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>We can use axis to set axis properties easily.<jupyter_code>X = np.array([2,4,6,8,10])
Y = np.array([15,29,2,44,9])
plt.plot(X,Y)
#We can set xlimits and ylimits for the plots in the following format [xmin,xmax,ymin,ymax].
plt.axis([0,6,0,20])
plt.show()<jupyter_output><empty_output><jupyter_text>Graph Styles Grid style can be used to show grids on graphs.<jupyter_code>plt.grid(True)
plt.show()<jupyter_output><empty_output><jupyter_text>We can do axis scaling to scale the X and Y axis using the classes xscale and yscale respectively.Scaling can be linear, logarithmic, etc.<jupyter_code>X = np.array([2,4,6,8,10])
Y = np.array([15,29,2000,44,9])
plt.xscale('linear')
#By default, we have linear scaling
plt.yscale('log')
plt.plot(X,Y)
plt.show()<jupyter_output><empty_output><jupyter_text>Different variations for graph plotting  Basic pie chart We next come to a fancier, more interesting way of representing data – pie graphs. Pie charts can be plotted very easily using the pie() function. We need to specify the sizes of each portion in the chart in a list.Once you plot the pie chart, you might notice that the chart isn’t round – which can be remedied using the axis() function and passing it the parameter ‘equal’.We’re done with our basic pie chart – how else can we customise it? We can pass it the ‘colors’ parameter and specify the colours of each section, and also give each section labels using the ‘labels’ parameter.How do we display information on the chart itself? We can display the percentage of each section of the pie by giving the parameter ‘autopct’. The autopct parameter needs a function (in the form of a string) that demonstrates how to display the percentage on the chart – for instance, ‘%.2f%%’ will display the percentages with two digits to the right of decimal. And it is not necessary that just the percentages can be displayed on the pie chart; we can pass any function we wish into the autopct parameter and it’ll decide the values on its own.You must have seen in several places that sometimes, for more interesting insight, a certain part of the pie chart is usually shown to be slightly out of the pie – a way of highlighting it. We can do that by passing the ‘explode’ parameter and giving it the values by which each section should be pushed out of the pie chart. A value of 1 indicated that the section is to be pushed entirely out of the pie.There are many, many other parameters we can pass to the pie() function to make our graph even better and informative. For instance, the counterclock parameter can be used to specify fractions direction, clockwise or counter-clockwise. The wedgeprops parameter takes in a dictionary of arguments passed to the wedge objects making the pie. For example, you can pass in wedgeprops = {'linewidth': 3} to set the width of the wedge border lines equal to 3.<jupyter_code># Plot a pie chart

pieLabels = ['Asia', 'Africa', 'Europe', 'North America', 'South America']
populationShare = [59.69, 16, 9.94, 7.79, 5.68]

figureObject, axesObject = plt.subplots()

axesObject.pie(populationShare,labels=pieLabels,autopct='%.1f%%',startangle=90, wedgeprops = {'linewidth': 5})
axesObject.axis('equal')
plt.show()
# Pie chart, where the slices will be ordered and plotted counter-clockwise:
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
explode = (0, 0.1, 0, 0)  
# only "explode" the 2nd slice (i.e. 'Hogs')

plt.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True, startangle=90)
plt.axis('equal')  # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()<jupyter_output><empty_output><jupyter_text>Histograms<jupyter_code>mu, sigma = 100, 15
x = mu + sigma*np.random.randn(10000)

# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='green', alpha=0.75)

# add a 'best fit' line
# y = mlab.normpdf( bins, mu, sigma)
# l = plt.plot(bins, y, 'r--', linewidth=1)

plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.axis([40, 160, 0, 0.03])
plt.grid(True)

plt.show()<jupyter_output><empty_output><jupyter_text>We can save the current plots or graphs using savefig.<jupyter_code>X = np.array([1,2,3,4])
Y = np.array([13,9,78,45])
plt.plot(X,Y)
plt.ylabel("Some random values")
plt.xlabel("Points")
plt.title("Plotting random values v/s data points")
plt.savefig("figure.png")
#Saves the plot with filename figure.png in the same directory<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10062797911780283, 'fraction_numerical': 0.02451388363471287, 'mean_word_length': 4.784682713347921, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 58, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '34588', 'license': 'Apache-2.0', 'n_tokens_mistral': 4359, 'n_tokens_neox': 4035, 'n_words': 1873, 'path': 'notes/6 graphs/GRAPHS.ipynb', 'repo_name': 'subhendu17620/ML-Coding-Ninjas', 'size': '13217'}