<jupyter_start><jupyter_text>Matplotlib example workflow<jupyter_code># 0. import Matplotlib  and get it ready for plotting in Jupyter
%matplotlib inline
import matplotlib.pyplot as plt

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

#2. Setup plot
fig,ax = plt.subplots(figsize=(10,10))

#3. Plot data
ax.plot(x,y)

#4. Customize Plot
ax.set(title="Simple Plot",
      xlabel="x-axis",
      ylabel="y-axis")

#5. Save and show (you can save the whole figure)
fig.savefig("sample-plot.png")<jupyter_output><empty_output><jupyter_text>Making figures with NumPy arraysWe want:* Line Plot* Scatter Plot* Bar plot* Histogram* Subplots<jupyter_code>import numpy as np
#  Create some data
x=np.linspace(0, 10, 100)
x[:10]
#Plot the data
fig, ax=plt.subplots()
ax.plot(x,x**2);
fig,ax=plt.subplots()
ax.scatter(x,np.exp(x))
# Another scatter plot
fig, ax=plt.subplots()
ax.scatter(x, np.sin(x));
# Make a plot from dictionary
nut_butter_prices = {"Almond butter": 10,
                     "Peanut butter": 8,
                    "Cashew butter": 12}
fig, ax=plt.subplots()
ax.bar(nut_butter_prices.keys(),nut_butter_prices.values())
ax.set(title="Dan's Nut butter store",
       ylabel="Price ($)");
fig, ax=plt.subplots()
ax.barh(list(nut_butter_prices.keys()), list(nut_butter_prices.values()));
#Make some data
x= np.random.randn(1000)
fig, ax=plt.subplots()
ax.hist(x);
# Subplot option 1
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_prices.keys(), nut_butter_prices.values());
ax4.hist(np.random.randn(1000));
#Subplot option 2
fig, ax=plt.subplots(nrows=2,
                     ncols=2,
                    figsize=(10,5))
#Plot to each different 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_prices.keys(), nut_butter_prices.values());
ax[1, 1].hist(np.random.randn(1000));<jupyter_output><empty_output><jupyter_text>Plotting from pandas DataFrames<jupyter_code>import pandas as pd
# Make a data-frame
car_sales = pd.read_csv("car-sales.csv")
car_sales
ts = pd.Series(np.random.randn(1000), index = pd.date_range("1/1/2020", periods = 1000))
ts
ts = ts.cumsum()
ts.plot()
car_sales
car_sales["Price"] = car_sales["Price"].str.replace('[\$\,\.]','')
car_sales
car_sales["Price"] = car_sales["Price"].str[:-2]
car_sales
car_sales["Sale Date"] = pd.date_range("1/1/2020", periods= len(car_sales))
car_sales
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");
#Reassign price column to int
car_sales["Price"]=car_sales["Price"].astype(int)
#Plot scatter plot with price column as numeric
car_sales.plot(x="Odometer (KM)",y="Price",kind="scatter")
#Bar graph
x=np.random.rand(10,4)
x
#Turn it into a data-frame
df=pd.DataFrame(x, columns=['a','b','c','d'])
df
df.plot.bar();
df.plot(kind="bar");
car_sales
car_sales.plot(x="Make",y="Odometer (KM)",kind="bar");
#Histograms
car_sales["Odometer (KM)"].plot.hist();
car_sales["Odometer (KM)"].plot(kind="hist");
car_sales["Odometer (KM)"].plot.hist(bins=20);
car_sales["Odometer (KM)"].plot.hist(bins=10);
heart_disease=pd.read_csv("heart-disease.csv");
heart_disease
#Create a histogram
heart_disease["age"].plot.hist(bins=50);
heart_disease.head()
heart_disease.plot.hist(figsize=(10,30) ,subplots=True);<jupyter_output><empty_output><jupyter_text>Which one should we use? (pyplot vs matplotlib OO method?)* When plotting something quickly it's ok to use the pyplot method* When plotting something more advanced, use the OO method<jupyter_code>over_50 = heart_disease[heart_disease["age"]>50]
over_50
over_50.plot(kind='scatter',x='age',y='age',c='target');
# OO method
fix, ax= plt.subplots(figsize=(10,6))
over_50.plot(kind='scatter',x='age',y='chol',c='target', ax= ax)
ax.set_xlim([45, 100])
# OO method from scratch
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 the plot
ax.set(title="Heart Disease and Cholestrol Levels", xlabel="Age", ylabel="Cholestrol");

#Add a legend
ax.legend(*scatter.legend_elements(), title="Target");

#Add a horizontal line
ax.axhline(over_50["chol"].mean(), linestyle="--");
# Subplot of chol, age, thalach
fig, (ax0, ax1)= plt.subplots(nrows=2, ncols=1, figsize=(10,10), sharex=True)

#Add data to ax0
scatter = ax0.scatter(x=over_50["age"], y=over_50["chol"], c=over_50["target"])

#Customize ax0
ax0.set(title="Heart Disease and Cholestrol Levels", ylabel="Cholestrol")
#Add a legend to ax0
ax0.legend(*scatter.legend_elements(),title="Target")
#Add a mean line
ax0.axhline(y=over_50["chol"].mean(), linestyle="--");

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

#Add a title to the figure
fig.suptitle("Heart Disease Analysis", fontsize=16, fontweight="bold");<jupyter_output><empty_output><jupyter_text>Customizing MatplotLib plots and getting stylish<jupyter_code># See the different available styles
plt.style.available
car_sales["Price"].plot();
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
x = np.random.randn(10, 4)
x
df = pd.DataFrame(x, columns=['a','b', 'c', 'd'])
df
ax = df.plot(kind='bar')
type(ax)
#Customize our plot with the set() method
ax=df.plot(kind="bar")
#Add some labels and a title
ax.set(title="Random Number Bar Graph from DataFrame",
       xlabel="Row number",
       ylabel="Random number")
#Make the legend visible
ax.legend().set_visible(True)
# Set the style
plt.style.use('seaborn-whitegrid')

# OO method from scratch
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="winter")

# Customize the plot
ax.set(title="Heart Disease and Cholestrol Levels",
       xlabel="Age",
       ylabel="Cholestrol")

#Add a legend
ax.legend(*scatter.legend_elements(), title="Target")

#Add a horizontal line
ax.axhline(over_50["chol"].mean(),
           linestyle="--");
# Subplot of chol, age, thalach
fig, (ax0, ax1)= plt.subplots(nrows=2, ncols=1, figsize=(10,10), sharex=True)

#Add data to ax0
scatter = ax0.scatter(x=over_50["age"], 
                      y=over_50["chol"], 
                      c=over_50["target"],
                     cmap="winter")

#Customize ax0
ax0.set(title="Heart Disease and Cholestrol Levels", ylabel="Cholestrol")
ax0.set_xlim([50,80])
#Add a legend to ax0
ax0.legend(*scatter.legend_elements(),title="Target")
#Add a mean line
ax0.axhline(y=over_50["chol"].mean(), linestyle="--");

#Add data to ax1
scatter = ax1.scatter(x=over_50["age"],
                      y=over_50["thalach"],
                      c=over_50["target"],
                     cmap="winter")
#Customize ax1
ax1.set(title="Heart Disease and Max Heart Rate",
        xlabel="Age",
        ylabel="Max Heart Rate");
ax1.set_xlim([50, 80])
ax1.set_ylim([60, 200])
#Add a legend to ax1
ax1.legend(*scatter.legend_elements(),title="Target")
#Add a mean line
ax1.axhline(y=over_50["thalach"].mean(), linestyle="--");

#Add a title to the figure
fig.suptitle("Heart Disease Analysis", fontsize=16, fontweight="bold");
fig.savefig("heart-disease-analysis-plot.png")<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.17651496102589892, 'fraction_numerical': 0.03256223283882324, 'mean_word_length': 5.054033485540335, 'pattern_counts': {'":': 3, '<': 21, '<?xml version=': 0, '>': 22, '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': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '658523', 'license': 'MIT', 'n_tokens_mistral': 3209, 'n_tokens_neox': 2934, 'n_words': 633, 'path': 'Introduction to MatPlotLib.ipynb', 'repo_name': 'tebalaji/Data-Science-Python', 'size': '7954'}