Search icon CANCEL
Subscription
0
Cart icon
Close icon
You have no products in your basket yet
Save more on your purchases!
Savings automatically calculated. No voucher code required
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Big Data Analysis with Python

You're reading from  Big Data Analysis with Python

Product type Book
Published in Apr 2019
Publisher Packt
ISBN-13 9781789955286
Pages 276 pages
Edition 1st Edition
Languages
Authors (3):
Ivan Marin Ivan Marin
Profile icon Ivan Marin
Ankit Shukla Ankit Shukla
Profile icon Ankit Shukla
Sarang VK Sarang VK
Profile icon Sarang VK
View More author details

Table of Contents (11) Chapters

Big Data Analysis with Python
Preface
1. The Python Data Science Stack 2. Statistical Visualizations 3. Working with Big Data Frameworks 4. Diving Deeper with Spark 5. Handling Missing Values and Correlation Analysis 6. Exploratory Data Analysis 7. Reproducibility in Big Data Analysis 8. Creating a Full Analysis Report Appendix

Chapter 02: Statistical Visualizations Using Matplotlib and Seaborn


Activity 4: Line Graphs with the Object-Oriented API and Pandas DataFrames

  1. Import the required libraries in the Jupyter notebook and read the dataset from the Auto-MPG dataset repository:

    %matplotlib inline
    import matplotlib as mpl
    import matplotlib.pyplot as pltimport numpy as np
    import pandas as pd
    
    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
    df = pd.read_csv(url)
  2. Provide the column names to simplify the dataset, as illustrated here:

    column_names = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'year', 'origin', 'name']
  3. Now read the new dataset with column names and display it:

    df = pd.read_csv(url, names= column_names, delim_whitespace=True)
    df.head()

    The plot is as follows:

    Figure 2.29: The auto-mpg DataFrame

  4. Convert the horsepower and year data types to float and integer using the following command:

    df.loc[df.horsepower == '?', 'horsepower'] = np.nan
    df['horsepower'] = pd.to_numeric(df['horsepower'])
    df['full_date'] = pd.to_datetime(df.year, format='%y')
    df['year'] = df['full_date'].dt.year
  5. Let's display the data types:

    df.dtypes

    The output is as follows:

    Figure 2.30: The data types

  6. Now plot the average horsepower per year using the following command:

    df.groupby('year')['horsepower'].mean().plot()

    The output is as follows:

    Figure 2.31: Line plot

Activity 5: Understanding Relationships of Variables Using Scatter Plots

  1. Import the required libraries into the Jupyter notebook and read the dataset from the Auto-MPG dataset repository:

    %matplotlib inline
    import pandas as pd
    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
    df = pd.read_csv(url)
  2. Provide the column names to simplify the dataset as illustrated here:

    column_names = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'year', 'origin', 'name']
  3. Now read the new dataset with column names and display it:

    df = pd.read_csv(url, names= column_names, delim_whitespace=True)
    df.head()

    The plot is as follows:

    Figure 2.32: Auto-mpg DataFrame

  4. Now plot the scatter plot using the scatter method:

    fig, ax = plt.subplots()
    ax.scatter(x = df['horsepower'], y=df['weight'])

    The output will be as follows:

    Figure 2.33: Scatter plot using the scatter method

Activity 6: Exporting a Graph to a File on Disk

  1. Import the required libraries in the Jupyter notebook and read the dataset from the Auto-MPG dataset repository:

    %matplotlib inline
    import pandas as pd
    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
    df = pd.read_csv(url)
  2. Provide the column names to simplify the dataset, as illustrated here:

    column_names = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'year', 'origin', 'name']
  3. Now read the new dataset with column names and display it:

    df = pd.read_csv(url, names= column_names, delim_whitespace=True)
  4. Create a bar plot using the following command:

    fig, ax = plt.subplots()
    df.weight.plot(kind='hist', ax=ax)

    The output is as follows:

    Figure 2.34: Bar plot

  5. Export it to a PNG file using the savefig function:

    fig.savefig('weight_hist.png')

Activity 7: Complete Plot Design

  1. Import the required libraries in the Jupyter notebook and read the dataset from the Auto-MPG dataset repository:

    %matplotlib inline
    import pandas as pd
    import numpy as np
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import seaborn as sns
    
    url = "https://archive.ics.uci.edu/ml/machine-learning-databases/auto-mpg/auto-mpg.data"
    df = pd.read_csv(url)
  2. Provide the column names to simplify the dataset, as illustrated here:

    column_names = ['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'year', 'origin', 'name']
  3. Now read the new dataset with column names and display it:

    df = pd.read_csv(url, names= column_names, delim_whitespace=True)
  4. Perform GroupBy on year and cylinders, and unset the option to use them as indexes:

    df_g = df.groupby(['year', 'cylinders'], as_index=False)
  5. Calculate the average miles per gallon over the grouping and set year as index:

    df_g = df_g.mpg.mean()
  6. Set year as the DataFrame index:

    df_g = df_g.set_index(df_g.year)
  7. Create the figure and axes using the object-oriented API:

    import matplotlib.pyplot as plt
    fig, axes = plt.subplots()
  8. Group the df_g dataset by cylinders and plot the miles per gallon variable using the axes created with size (10,8):

    df = df.convert_objects(convert_numeric=True)
    df_g = df.groupby(['year', 'cylinders'], as_index=False).horsepower.mean()
    df_g = df_g.set_index(df_g.year)
  9. Set the title, x label, and y label on the axes:

    fig, axes = plt.subplots()
    df_g.groupby('cylinders').horsepower.plot(axes=axes, figsize=(12,10))
    _ = axes.set(
        title="Average car power per year",
        xlabel="Year",
        ylabel="Power (horsepower)"
        
    )

    The output is as follows:

    Figure 2.35: Line plot for average car power per year (without legends)

  10. Include legends, as follows:

    axes.legend(title='Cylinders', fancybox=True)

    Figure 2.36: Line plot for average car power per year (with legends)

  11. Save the figure to disk as a PNG file:

    fig.savefig('mpg_cylinder_year.png')
lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}