<jupyter_start><jupyter_text>What is Matplotlib?It is a python plotting library, it allows us to turn our data into figures. Why Matplotlib?- Built on Numpy arrays(python)- Integrates directly with pandas- Can create basic or advanced plots- Simple to use interface. Workflow of Matplotlib?1. Create data2. Create plot(figure)3. plot data(axes on figure)4. customize plot5. Save/share plot  Importing and Using Matplotlib :<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
plt.plot()
# use ; to remove list as output
# or u can write plt.show() in 2nd line
plt.plot();
plt.plot([1,2,3,4]);
x = [1, 2, 3, 4]
y = [11, 22, 33, 44]
plt.plot(x, y)<jupyter_output><empty_output><jupyter_text>There are mainlyn 2 ways to plot data in matplotlib1. pyplot API (less flexible, method 1 and 2)2. object-orented API (method 3)<jupyter_code># 1st method
fig = plt.figure() # create a figure
ax = fig.add_subplot() # add some axes
plt.show()
# 2nd method
fig = plt.figure() # create a figure
ax = fig.add_axes([1, 1, 1, 1])
ax.plot(x, y) # add some data
plt.show()
# 3rd method(recommended by matplotlib)
fig, ax = plt.subplots()
ax.plot(x, [50, 100, 200, 400]); # add some data
type(fig), type(ax)<jupyter_output><empty_output><jupyter_text>Anatomy Of A Matplotlib Figure(plot) :   Matplotlib example workflow<jupyter_code># 1. import matplotlib and get it ready for plotting 
%matplotlib inline
import matplotlib.pyplot as plt

# 2. Prepare data
x = [1, 2, 3, 4]
y = [11, 33, 22, 44]

# 3. setup plot
fig,ax = plt.subplots(figsize=(10, 5)) # figsize = (width, height)

# 4 . plot data
ax.plot(x, y)

# 5. customize plot
ax.set(title='Simple Plot', xlabel='x-axis', ylabel='y-axis')

# 6. Save and show
fig.savefig('./sample-plot.png')<jupyter_output><empty_output><jupyter_text>Types of Plot :1. Line plot2. Scatter plot3. Bar plot4. Histogram plot5. subplot<jupyter_code># Create some data

x = np.linspace(0, 10, 100) # return 100 random val between 0 to 10
x[:10]
# 1. line plot
fig,ax = plt.subplots()
ax.plot(x, x**2); # default is line plot
# 2. Scatter plot
fig, ax = plt.subplots()
ax.scatter(x, np.exp(x));
fig,ax = plt.subplots()
ax.scatter(x, np.sin(x));
# 3. Bar graph(from dictionary)
nut_butter = {'Almond butter': 10,
             "Peanut butter": 8,
             "Cashew butter": 12}
fig,ax = plt.subplots()
ax.bar(nut_butter.keys(), nut_butter.values())
ax.set(title="Dan's Nut Butter Store", ylabel="Price ($)");
# horizontal bar graph
fig, ax = plt.subplots()
# need LIST as input for horizontal bar
ax.barh(list(nut_butter.keys()), list(nut_butter.values()));
# 4. histogram
x = np.random.randn(1000) # return val from normal distribution
fig,ax = plt.subplots()
ax.hist(x);<jupyter_output><empty_output><jupyter_text>Two ways to make subplot<jupyter_code># 1st way of Subplot
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2, figsize=(10,5))

# Plot to each different axis
ax1.plot(x, x/2)
ax2.scatter(np.random.random(10), np.random.random(10))
ax3.bar(nut_butter.keys(), nut_butter.values())
ax4.hist(np.random.randn(1000));
# 2nd way of Subplot
fig,ax = plt.subplots(nrows=2, ncols=2, figsize=(10,5))

# Plot to each diffrent index
ax[0, 0].plot(x, x/2)
ax[0, 1].scatter(np.random.random(10), np.random.random(10))
ax[1, 0].bar(nut_butter.keys(), nut_butter.values())
ax[1, 1].hist(np.random.randn(1000));<jupyter_output><empty_output><jupyter_text>Plotting From Pandas DataFrames :<jupyter_code># Make a dataframe
car_sales = pd.read_csv('../Introduction_to_pandas/car-sales.csv')
car_sales
np.random.seed(10)
ts = pd.Series(np.random.randn(1000),
               index=pd.date_range('12/11/2020', periods=1000))
ts[:10], ts[:10].cumsum() # cummulative sum<jupyter_output><empty_output><jupyter_text>the next cell shows that pandas is built over matplotlib, as we can use `plot` method in the pandas series `ts`.<jupyter_code>ts.plot();
car_sales['Price'] = car_sales['Price'].str.replace('[\$\,\.]', '')

car_sales['Price'] = car_sales['Price'].str[:-2]
car_sales
car_sales['Sale Date'] = pd.date_range('12/11/2020', periods=len(car_sales))
car_sales
# price column have all string values
type(car_sales['Price']), type(car_sales['Price'][0])
car_sales['Total Sales'] = car_sales['Price'].astype(int).cumsum()
car_sales
# Let's plot the total sales
car_sales.plot(x='Sale Date', y='Total Sales');
# changing price column dtype from str to int
car_sales['Price'] = car_sales['Price'].astype(int)
car_sales.plot(x='Odometer (KM)', y='Price', kind='scatter');
# Bar graph from pandas
x = np.random.rand(10, 4)

# Turn it into a dataframe

df = pd.DataFrame(x, columns=['a', 'b', 'c', 'd'])
df
# we can also write kind='bar' inside plot method to get same result
df.plot.bar(figsize=(10, 5));
car_sales
car_sales.plot(x='Make', y='Odometer (KM)', kind='bar', figsize=(10, 5));
# Histogram from pandas

car_sales['Odometer (KM)'].plot.hist();
# bins are number of bars in histogram (default=10)
car_sales['Odometer (KM)'].plot.hist(bins=5);
# Let's Try on another dataset
heart_disease = pd.read_csv('./heart-disease.csv')
heart_disease[:10]
# Create a histogram of age
heart_disease['age'].plot.hist(bins=50, figsize=(10, 5));
heart_disease.head()
# the x axis is same for all axis which is not good
heart_disease.plot.hist(subplots=True, figsize=(10, 20));<jupyter_output><empty_output><jupyter_text>Which one should you use? (pyplot vs OO)- when plotting quickly(just to check data), then `pyplot` is good.- but when plotting something advance use `OO method`.<jupyter_code>heart_disease.head()
# taking data of patients over age 50
over_50 = heart_disease[heart_disease['age'] > 50]
over_50.head()
len(over_50), len(heart_disease)<jupyter_output><empty_output><jupyter_text>using pyplot(can't see age in x axis)<jupyter_code># c is for color
over_50.plot.scatter(x='age', y='chol', c='target');<jupyter_output><empty_output><jupyter_text>OO method mixed with pyplot(can see age in x axis)<jupyter_code>fig, ax = plt.subplots(figsize=(10, 5))
over_50.plot(kind='scatter', x='age', y='chol', c='target', ax=ax);

# to use range in x axis
# ax.set_xlim([45, 100]);<jupyter_output><empty_output><jupyter_text>OO method from Scratch<jupyter_code>fig, ax = plt.subplots(figsize=(10, 6))

# Plot the data
scatter = ax.scatter(x=over_50['age'],
                    y=over_50['chol'],
                    c=over_50['target'])

# Customize
ax.set(title='Heart Disease and Cholesterol Levels',
      xlabel='Age', ylabel='Cholesterol');

# Add a legend
# grabbing target values from scatter and adding legend to each
ax.legend(*scatter.legend_elements(), title='Target');

# Add a horizontal mean line
ax.axhline(over_50['chol'].mean(), linestyle='--');
over_50.head()<jupyter_output><empty_output><jupyter_text>Subplot of chol, age thalach<jupyter_code>fig, (ax0, ax1) = plt.subplots(nrows=2, ncols=1, figsize=(10, 10),
                              sharex=True) # both axis share x axis

# Add data to axis 0
scatter = ax0.scatter(x=over_50['age'],
                     y=over_50['chol'],
                     c=over_50['target'])
# Customizing axis 0
ax0.set(title='Heart Disease and Cholestrol Levels',
        xlabel='Age', ylabel='Cholestrol')
ax0.legend(*scatter.legend_elements(), title='Target')
ax0.axhline(y=over_50['chol'].mean(), linestyle='--')


# Add data to axis 1
thalach = ax1.scatter(x=over_50['age'],
                     y=over_50['thalach'],
                     c=over_50['target'])
# Customizing axis 1
ax1.set(title='Heart Disease and Max Heart Rate',
       xlabel='Age', ylabel='Max Heart Rate')
ax1.legend(*scatter.legend_elements(), title='Target')
ax1.axhline(y=over_50['thalach'].mean(), linestyle='--')

# Add title to entire figure
fig.suptitle('Heart Disease Analysis', 
             fontsize=16, fontweight='bold');<jupyter_output><empty_output><jupyter_text>Customizing Your Plots :<jupyter_code>car_sales.head()
car_sales['Price'].plotot();
# See different styles available
plt.style.available
# this style added white grid
plt.style.use('seaborn-whitegrid')
car_sales['Price'].plot();
plt.style.use('seaborn')
car_sales['Price'].plot();
car_sales.plot(x='Odometer (KM)', y='Price', kind='scatter');
plt.style.use('ggplot')
car_sales['Price'].plot();
# Create some data
np.random.seed(3)
x= np.random.randn(10, 4)
x
df = pd.DataFrame(x, columns=['a', 'b', 'c', 'd'])
df
ax = df.plot(kind='bar')
# Customize our plot with set() method
ax = df.plot(kind='bar')

# Add some label and title
ax.set(title='Random Number Bar Graph from dataframe',
      xlabel='Row number', ylabel='Random number')

# Make the legend visible(for plots where legends not visible)
ax.legend().set_visible(True)<jupyter_output><empty_output><jupyter_text>Customizing Your Plots 2 :<jupyter_code># setting style
plt.style.use('seaborn-whitegrid')

fig, ax = plt.subplots(figsize=(10, 6))

# Plot the data
scatter = ax.scatter(x=over_50['age'],
                    y=over_50['chol'],
                    c=over_50['target'],
                    cmap='plasma') # changes the colour(color maps)

# Customize
ax.set(title='Heart Disease and Cholesterol Levels',
      xlabel='Age', ylabel='Cholesterol');

# Add a legend
# grabbing target values from scatter and adding legend to each
ax.legend(*scatter.legend_elements(), title='Target');

# Add a horizontal mean line
ax.axhline(over_50['chol'].mean(), linestyle='--');
# Customizing the y and x limitation

fig, (ax0, ax1) = plt.subplots(nrows=2, ncols=1, figsize=(10, 10),
                              sharex=True) # both axis share x axis

# Add data to axis 0
scatter = ax0.scatter(x=over_50['age'],
                     y=over_50['chol'],
                     c=over_50['target'],
                     cmap='plasma')
# Customizing axis 0
ax0.set(title='Heart Disease and Cholestrol Levels',
        xlabel='Age', ylabel='Cholestrol')
ax0.legend(*scatter.legend_elements(), title='Target')
ax0.axhline(y=over_50['chol'].mean(), linestyle='--')

# Change ax0 the x axis limits
ax0.set_xlim([50, 80])



# Add data to axis 1
thalach = ax1.scatter(x=over_50['age'],
                     y=over_50['thalach'],
                     c=over_50['target'],
                     cmap='winter')
# Customizing axis 1
ax1.set(title='Heart Disease and Max Heart Rate',
       xlabel='Age', ylabel='Max Heart Rate')
ax1.legend(*scatter.legend_elements(), title='Target')
ax1.axhline(y=over_50['thalach'].mean(), linestyle='--')

# Change ax1 the x axis limits
ax1.set_xlim([50, 80]) # not necessary since both axis share same x

# Change ax1 the y axis limits
ax1.set_ylim([60, 200]) # not necessary since both axis share same x

# Add title to entire figure
fig.suptitle('Heart Disease Analysis', 
             fontsize=16, fontweight='bold');<jupyter_output><empty_output><jupyter_text>Saving And Sharing Your Plots :<jupyter_code># one way is to right click and save the graph
fig.savefig('heart-disease-analysis.png')<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.15534688668064545, 'fraction_numerical': 0.03163460661865257, 'mean_word_length': 4.683937823834197, 'pattern_counts': {'":': 2, '<': 61, '<?xml version=': 0, '>': 62, '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': '15', 'dir': 'jupyter-structured-clean-dedup', 'id': '574792', 'license': 'MIT', 'n_tokens_mistral': 4235, 'n_tokens_neox': 3863, 'n_words': 1011, 'path': 'Course/Complete Machine Learning and Data Science/Matplotlib/.ipynb_checkpoints/Introduction to matplotlib-checkpoint.ipynb', 'repo_name': 'naw7az/quickRepo', 'size': '10969'}