<jupyter_start><jupyter_text>Introduction to Matplotlib<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
plt.plot()
plt.plot();
plt.plot()
plt.show()
plt.plot([1, 2, 3, 4]);
x = [1, 2, 3, 4]
y = [11, 22, 33, 44]
plt.plot(x, y);
# 1st Method
fig = plt.figure()
fig.add_subplot(2, 3, 1)
fig.add_subplot(2, 3, 2)
fig.add_subplot(2, 3, 3)
fig.add_subplot(2, 3, 4)
fig.add_subplot(2, 3, 5)
fig.add_subplot(2, 3, 6)
plt.show()
# 2nd Method
fig = plt.figure()
ax = fig.add_axes([1, 1, 1, 1], label='abc')
fig.add_axes([2, 2, 2, 2])
plt.show()
# 3rd Method
fig, ax = plt.subplots(figsize=(10, 10))
plt.plot(x, y);<jupyter_output><empty_output><jupyter_text>Matplotlib Example Workflow<jupyter_code>%matplotlib inline
import matplotlib.pyplot as plt

y = np.random.normal(size=(10))
x = np.linspace(1, 10, num=10)

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

ax.plot(x, y)

ax.set(title='Sample Normal Data',
      xlabel='Data Points',
      ylabel='Normal Data Points')

fig.savefig('../images/sample-normal-data.png')<jupyter_output><empty_output><jupyter_text>Different types of plots* Scatter* Bar* Hist* Line* Subplots<jupyter_code>x = np.linspace(0, 10, 100)
x[:10]
fig, ax = plt.subplots()
ax.plot(x, x**2);
fig, ax = plt.subplots()
ax.scatter(x, np.exp(x));
fig, ax = plt.subplots()
ax.scatter(x, np.sin(x));
nut_prices = {'almond': 100,
             'peanut': 200,
             'cashew': 300}
fig, ax = plt.subplots()
ax.bar(nut_prices.keys(), nut_prices.values())
ax.set(title='Nut Prices',
      xlabel='Nuts',
      ylabel='Prices')
plt.show()
a = np.random.randn(1000)
fig, ax = plt.subplots()
ax.barh(list(nut_prices.keys()), list(nut_prices.values()));
fig, ax = plt.subplots()
ax.hist(a);
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2,
                                             ncols=2,
                                             figsize=(10, 5))
ax1.plot(x, x**2);
ax2.scatter(np.random.random(10), np.random.random(10));
ax3.bar(nut_prices.keys(), nut_prices.values());
ax4.hist(a);
fig, ax = plt.subplots(nrows=2,
                       ncols=2,
                       figsize=(10, 5))
ax[0, 0].plot(x, x**3);
ax[0, 1].scatter(np.random.random(10), np.random.random(10));
ax[1, 0].bar(nut_prices.keys(), nut_prices.values())
ax[1, 1].hist(np.random.randn(1000));<jupyter_output><empty_output><jupyter_text>Dataframe plotting<jupyter_code>car_sales = pd.read_csv('../pandas/car-sales.csv')
car_sales
# Plot from pd Series
S1 = pd.Series(np.random.randn(1000),
               index=pd.date_range('1/1/2020', periods=1000))
S1
S1 = S1.cumsum()
S1.plot()
# Plot Dataframe using pyplot on car_sales
car_sales
car_sales['Price'].str.replace("[\$\,]|\.\d*", "").apply(int)
car_sales['Price'] = car_sales['Price'].str.replace("[\$\,]|\.\d*", "").apply(int)
car_sales
car_sales['Sale Date'] = pd.date_range('1/1/2020', periods=len(car_sales))
car_sales
car_sales['Total Sale ($)'] = car_sales['Price'].cumsum()
car_sales
car_sales['Price'].dtype
car_sales.dtypes
car_sales['Total Sale ($)'].plot();
car_sales.plot(x='Sale Date', y='Total Sale ($)', xlabel='Dates', ylabel='Sales');
car_sales.plot(x='Odometer (KM)', y='Price', kind='scatter')
car_sales
car_sales.plot(x='Make', y='Price', kind='bar');
x = np.random.rand(10, 4)
x

df = pd.DataFrame(x, columns=['a', 'b', 'c', 'd'])
df
df.plot.bar();
df.plot(kind='bar');
car_sales
car_sales['Price'].plot.hist();
car_sales.plot(bins=20, kind='hist');
car_sales['Odometer (KM)'].plot.hist(bins=20);
# let's try on different dataset
heart_disease = pd.read_csv('../heart-disease.csv')
heart_disease
heart_disease['age'].plot.hist()
heart_disease.plot.hist(figsize=(10, 50), subplots=True);
heart_disease.head()
over_50 = heart_disease[heart_disease['age'] > 50]
over_50.head()
# Pyplot api method
over_50.plot(kind='scatter',
             x='age',
             y='chol',
             c='target',
             figsize=(10, 5));
# OO Method
fig, ax = plt.subplots(figsize=(10, 5))
over_50.plot(kind='scatter',
             x='age',
             y='chol',
             c='target',
             ax=ax);

ax.set_xlim([45, 80]);
## OO method simplified

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

scattey = ax.scatter(x=over_50['age'],
                     y=over_50['chol'],
                     c=over_50['target'])

ax.set(title='Heart Disease Cholesterol Level by Age',
       xlabel='Age',
       ylabel='Cholesterol');

ax.legend(*scattey.legend_elements(), title='Target');

ax.axhline(y=over_50['chol'].mean(),
          linestyle='--',
          c='red');<jupyter_output><empty_output><jupyter_text>Subplot with Cholesterol, Age and Max Heart Rate<jupyter_code>fig, ax = plt.subplots(nrows=2,
                       ncols=1,
                       figsize=(10, 12),
                       sharex=True)

scatter_chol = ax[0].scatter(x=over_50['age'],
                             y=over_50['chol'],
                             c=over_50['target'])

ax[0].set(title='Heart Disease Cholesterol Level by Age',
          ylabel='Cholesterol')

ax[0].legend(*scatter_chol.legend_elements(), title='Target')

ax[0].axhline(y=over_50['chol'].mean(), linestyle='--', c='red');

##

scatter_thal = ax[1].scatter(x=over_50['age'],
                             y=over_50['thalach'],
                             c=over_50['target'])

ax[1].set(title='Heart Disease Max Heart Rate by Age',
          xlabel='Age',
          ylabel='Max Heart Rate')

ax[1].legend(*scatter_thal.legend_elements(), title='Target')

ax[1].axhline(y=over_50['thalach'].mean(), linestyle=':', c='blue');

fig.suptitle('Heart Disease Plot', fontsize=16, fontweight='bold');<jupyter_output><empty_output><jupyter_text>Plot Styles<jupyter_code>plt.style.available
car_sales
plt.style.use('bmh')
car_sales['Price'].plot();
plt.style.use('ggplot')
car_sales['Price'].plot();
df = pd.DataFrame(np.random.randn(10, 4), columns=['a', 'b', 'c', 'd'])
df
p = df.plot(kind='bar');
p.set(title='Sample',
      xlabel='x',
      ylabel='y');
p.legend().set_visible(True);
plt.style.use('seaborn-whitegrid')
fig, ax = plt.subplots(figsize=(10, 6))

scattey = ax.scatter(x=over_50['age'],
                     y=over_50['chol'],
                     c=over_50['target'],
                     cmap='summer')

ax.set(title='Heart Disease Cholesterol Level by Age',
       xlabel='Age',
       ylabel='Cholesterol');

ax.legend(*scattey.legend_elements(), title='Target');

ax.axhline(y=over_50['chol'].mean(),
          linestyle='--',
          c='red');
fig, ax = plt.subplots(nrows=2,
                       ncols=1,
                       figsize=(10, 12),
                       sharex=True)

scatter_chol = ax[0].scatter(x=over_50['age'],
                             y=over_50['chol'],
                             c=over_50['target'],
                             cmap='winter')

ax[0].set(title='Heart Disease Cholesterol Level by Age',
          ylabel='Cholesterol')
ax[0].set_xlim([45, 80])

ax[0].legend(*scatter_chol.legend_elements(), title='Target')

ax[0].axhline(y=over_50['chol'].mean(), linestyle='--', c='red');

##

scatter_thal = ax[1].scatter(x=over_50['age'],
                             y=over_50['thalach'],
                             c=over_50['target'],
                             cmap='summer')

ax[1].set(title='Heart Disease Max Heart Rate by Age',
          xlabel='Age',
          ylabel='Max Heart Rate')

ax[1].set_ylim([60, 200])
ax[1].legend(*scatter_thal.legend_elements(), title='Target')

ax[1].axhline(y=over_50['thalach'].mean(), linestyle=':', c='blue');

fig.suptitle('Heart Disease Plot', fontsize=16, fontweight='bold');
fig
fig.savefig("heart-disease-risk-plot.png")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.19426792893269357, 'fraction_numerical': 0.035793022954221244, 'mean_word_length': 3.3180291153415453, 'pattern_counts': {'":': 0, '<': 25, '<?xml version=': 0, '>': 26, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '6', 'dir': 'jupyter-structured-clean-dedup', 'id': '369855', 'license': 'MIT', 'n_tokens_mistral': 3150, 'n_tokens_neox': 2854, 'n_words': 489, 'path': 'matplotlib/introduction-to-matplotlib.ipynb', 'repo_name': 'Siddharth2016/MLZTM-Exercises', 'size': '7711'}