<jupyter_start><jupyter_text>Basics of Data Science Using PythonIn this session, we will learn the basics of data science using Python. In the previous sessions, we already discussed about the basics of data science and the applications of data science. So, we will move forward to today's session where we will be covering many python modules and their applications.The modules covered in this session are,    Numpy    Pandas    Matplotlib  3. Learning Matplotlib  What is Matplotlib? Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK+. What are we going to learn?We are going to learn the following     Simple Line Plot    Simple Scatter Plots    Visualizing Errors    Density and Contour Plots    Multiple Subplots    Histogram    Visualization With Seaborn  Import Matplotlib<jupyter_code>import matplotlib.pyplot as plt
%matplotlib inline
# additional imports
import numpy as np<jupyter_output><empty_output><jupyter_text>DemoJust a demo line of code to show how plotting is done using matplotlib. Here we are using the pyplot module of matplotlib to plot values.<jupyter_code>x = np.linspace(0, 10, 100)
y = np.sin(x)
plt.plot(x, y)
plt.grid()<jupyter_output><empty_output><jupyter_text>1. Simple Line PlotLet's create a simple plot using matplotlib. We will create a list of values for x and corresponding random values for y. And we will plot it using plt.plot(x, y).<jupyter_code>x = [i for i in range(10)] # serializing x axis values
y = [item+np.random.randint(-50, 50)/10 for item in x] # randomizing the y axis values

plt.plot(x, y)
plt.title('Simple Line Plot') # to give the plot a title.
plt.grid() # to print the grid.
plt.show()<jupyter_output><empty_output><jupyter_text>2. Simple Scatter PlotLet's create a simple scatter plot using matplotlib. We will use the same previously generated values of x and y here. And we will plot it using plt.scatter(x, y).<jupyter_code>plt.scatter(x, y)
plt.title('Simple Scatter Plot') # to give the plot a title.
plt.grid() # to print the grid.
plt.show()<jupyter_output><empty_output><jupyter_text>3. Visualizing ErrorsLet's create a vizualization of error for two list of values using matplotlib. We will use the same previously generated values of x and y here. And we will plot it using plt.errorbar(x, y). For any scientific measurement, accurate accounting for errors is nearly as important, if not more important, than accurate reporting of the number itself. In visualization of data and results, showing these errors effectively can make a plotconvey much more complete information.<jupyter_code>plt.errorbar(x, y, yerr=2, fmt='.k') # xerr, yerr - error margin
plt.title('Error Visualization Plot') # to give the plot a title.
plt.grid() # to print the grid.
plt.show()<jupyter_output><empty_output><jupyter_text>4. Density and Contour PlotsSometimes it is useful to display three-dimensional data in two dimensions using contours or color-coded regions. There are three Matplotlib functions that can be helpful for this task: plt.contour for contour plots, plt.contourf for filled contour plots, and plt.imshow for showing images.<jupyter_code>def get_z(x, y):
    sqr_sum = x**2 + y**2
    return (np.sin(sqr_sum) + np.cos(sqr_sum))

xx = np.linspace(-10, 10, 100)
yy = np.linspace(-10, 10, 100)
X, Y = np.meshgrid(xx, yy)
Z = get_z(X, Y)

plt.contour(X, Y, Z)
plt.title('Plotting Conture of the defined function') # to give the plot a title.
#plt.grid() # to print the grid.
plt.show()
plt.contour(X, Y, Z, cmap='RdGy') # using cmap, we can change the plot styles
plt.title('Plotting Conture of the defined function') # to give the plot a title.
#plt.grid() # to print the grid.
plt.show()<jupyter_output><empty_output><jupyter_text>combine contour plots and image plots<jupyter_code>contours = plt.contour(X, Y, Z, 3, colors='black')
plt.clabel(contours, fontsize=6, inline=True)
plt.imshow(Z, extent=[-2, 2, -2, 2], origin='lower', cmap='RdGy', alpha=0.5)
plt.colorbar()<jupyter_output><empty_output><jupyter_text>5. Multiple SublotsLet's create a multiple subplots using pyplot. Here we will create 2X2 subplot with all the plots we created till now. We will use plt.subplot(2, 2, i) where 0 < i <= 4.<jupyter_code>plt.figure(figsize=(10, 8))

plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.title('Simple Line Plot') # to give the subplot a title.
plt.grid() # to print the grid.

plt.subplot(2, 2, 2)
plt.scatter(x, y)
plt.title('Simple Scatter Plot') # to give the subplot a title.
plt.grid() # to print the grid.

plt.subplot(2, 2, 3)
plt.errorbar(x, y, yerr=2, fmt='.k') # xerr, yerr - error margin
plt.title('Error Visualization Plot') # to give the subplot a title.
plt.grid() # to print the grid.

plt.subplot(2, 2, 4)
plt.contour(X, Y, Z)
plt.title('Plotting Conture of the defined function') # to give the subplot a title.

plt.suptitle('Combining All The Plots') # common title for all the inputs.

plt.show()<jupyter_output><empty_output><jupyter_text>6. HistogramLet us plot a histogram using matplotlib.<jupyter_code>data = np.random.randn(100) # randomly generated 100 data sample
plt.hist(data) # plotting generated data
plt.title('Plotting Histogram') # to give the subplot a title.
plt.grid() # to print the grid.
plt.show()<jupyter_output><empty_output><jupyter_text>Multiple HistogramsAvailable histtype values are = ['bar', 'barstacked', 'step',  'stepfilled']Change it according to your wish and plot.<jupyter_code>x1 = np.random.normal(-3, 2, 1000)
x2 = np.random.normal(3, 8, 1000)
x3 = np.random.normal(0, 5, 1000)

args = dict(histtype='stepfilled', alpha=0.8, density=True, bins=20)

plt.hist(x1, label='Type 1', **args)
plt.hist(x2, label='Type 2', **args)
plt.hist(x3, label='Type 3', **args)

plt.title('Plotting multiple histograms') # to give the subplot a title.
plt.grid() # to print the grid.

plt.show()<jupyter_output><empty_output><jupyter_text>7. Visualization With SeabornSeaborn provides an API on top of Matplotlib that offers sane choices for plot style and color defaults, defines simple high-level functions for common statistical plot types, and integrates with the functionality provided by Pandas DataFrames.<jupyter_code>import pandas as pd
import seaborn as sns

sns.set()<jupyter_output><empty_output><jupyter_text>Often in statistical data visualization, all we want is to plot histograms. Here we define a dataframe and plot histogram for both of it's columns.<jupyter_code>data = np.random.multivariate_normal([0,0], [[7, 2], [2, 2]], size=3000)
data = pd.DataFrame(data, columns=['A', 'B'])

for col in 'AB':
    plt.hist(data[col], density=True, alpha=0.5)<jupyter_output><empty_output><jupyter_text>Now plotting a smooth estimate of the distribution using a kernel density estimation, which Seaborn does with sns.kdeplot.<jupyter_code>for col in 'AB':
    sns.kdeplot(data[col], shade=True)<jupyter_output><empty_output><jupyter_text>Now, let's combine both the plots in a single figure.<jupyter_code>for col in 'AB':
    plt.hist(data[col], density=True, alpha=0.5)
    sns.kdeplot(data[col], shade=True)
plt.title('Plot using seaborn and matplotlib')
plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10420650095602295, 'fraction_numerical': 0.01638896476372576, 'mean_word_length': 5.1901944209636515, 'pattern_counts': {'":': 0, '<': 59, '<?xml version=': 0, '>': 57, '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': '644257', 'license': 'MIT', 'n_tokens_mistral': 2530, 'n_tokens_neox': 2358, 'n_words': 885, 'path': 'DataScience/DS_4_Data_Science_Using_Python/[DS-Tutorial-1] Basics_of_Data_Science - 3 - Matplotlib.ipynb', 'repo_name': 'alexAngshu/BitsAndBytes', 'size': '7322'}