Showing posts with label matplotlib. Show all posts
Showing posts with label matplotlib. Show all posts

Data Visualisation with Matplotlib || Fresco Play || 56869

Data Visualisation with Matplotlib - 56869

Matplotlib-1 - My First Plot

Task1

  • Create a function named test_the_plot.
  • Create a figure of size 12 inches in width, and 6 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Create a list t with values [7, 14, 21, 28, 35]
  • Create a list d with values [i*6 for i in t]
  • Draw a line, by plotting t values on X-Axis and d values on Y-Axis. Use the plot function. Label the line as d = 6t.
  • Label X-Axis as time (seconds).
  • Label Y-Axis as distance (meters).
  • Set Title as Time vs Distance Covered.
  • Limit data points on X-Axis from 0 to 40.
  • Limit data points on Y-Axis from 0 to 220.
  • Add a legend.
  • return the figure object

Note: The results of preliminary validation doesn't impact final scoring. In-depth scorings are done at a later stage.

Once you are in the Web IDE:

  1. Open prog.py in the jupyter lab the file and start your coding by following the instructions given above.
  2. Once you are done with the solution , then run the following commands in the terminal to check your solutions. Click File -> New -> Terminal, run the following commands
python3 prog.py
  1. After running the test cases, click the submit button and click on Submit Test to end the assessment.

Note - Here Rough_Work.ipynb can be used for rough work to get the solutions

Solution

import numpy as np
import matplotlib.pyplot as plt


def test_the_plot():
    fig = plt.figure(figsize=(12, 6))
    ax = fig.add_subplot(111)
    t = [7, 14, 21, 28, 35]
    d = [i * 6 for i in t]
    ax.plot(t, d, label='d = 6t')
    ax.set_xlabel('time (seconds)')
    ax.set_ylabel('distance (meters)')
    ax.set_title('Time vs Distance Covered')
    ax.set_xlim(0, 40)
    ax.set_ylim(0, 220)
    ax.legend("My First Plot")
    return fig

# Note: Do Not modify the below code
if __name__ == '__main__':
    import sys
    import subprocess
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'test_plot1-0.2-py3-none-any.whl'], stdout=subprocess.DEVNULL)
    from test_plot1 import matplotlib1
    usr_fig = test_the_plot()
    matplotlib1.save_answer(usr_fig)

Matplotlib-2 - Scatter Plots

Task1

  • Create a function named sine_wave_plot.
  • Create a figure of size 13 inches in width, and 4 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Create a numpy array arr_t with 250 values between 0.0 and 3.0. Use the 'linspace' method to generate 250 values.
  • Create a numpy array arr_v, such that arr_v = np.sin(2.5*np.pi*arr_t).
  • Pass arr_t and arr_v as variables to plot function and draw a red line passing through the selected 250 points. Label the line as sin(arr_t).
  • Label X-Axis as Time (seconds).
  • Label Y-Axis as Voltage (mv).
  • Set Title as Sine Wave.
  • Limit data on X-Axis from 0 to 2.
  • Limit data on Y-Axis from -1 to 1.
  • Mark major ticks on X-Axis at 0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, and 2.0.
  • Mark major ticks on Y-Axis at -1, 0, and 1.
  • Add a grid, whose linestyle is dashdot.
  • Add a legend.
  • return the figure object

Task2

  • Create a function named multi_curve_plot.
  • Create a figure of size 13 inches in width, and 4 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Create a numpy array arr_x with 25 values between 0.0 and 7.0. Use the 'linspace' method to generate 25 values.
  • Create three numpy arrays arr_y1, arr_y2 and arr_y3, using the expressions arr_y1 = arr_x, arr_y2 = arr_x**2 and arr_y3 = arr_x**3 respectively.
  • Draw a green colored line passing through arr_x and arr_y1, using the plot function. Mark the 25 data points on the line as upward pointed triangles. Label the line as y = arr_x.
  • Draw a blue colored line passing through arr_x and arr_y2, using the plot function. Mark the 25 data points on the line as squares. Label the line as y = arr_x**2.
  • Draw a red colored line passing through arr_x and arr_y3, using the plot function. Mark the 25 data points on the line as circles.
  • Label the line as y = arr_x**3.
  • Label X-Axis as arr_x.
  • Label Y-Axis as f(arr_x).
  • Set Title as Linear, Quadratic, & Cubic Equations.
  • Add a legend.
  • return the figure object

Task3

  • Create a function named scatter_plot.
  • Create a figure of size 13 inches in width, and 4 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Consider the list car_sales = [40, 65, 70, 40, 55, 60, 75, 60, 80, 95, 96, 105]. It represents the number of cars sold by a Company 'X' in each month of 2021, starting from January, 2021.
  • Create a list months containing numbers from 1 to 12.
  • Draw a scatter plot with variables months and car_sales as arguments. Mark the data points in green color. Use the scatter function for plotting.Label the points as car sales.
  • Limit data on X-Axis from 0 to 13.
  • Limit data on Y-Axis from 10 to 110.
  • Mark ticks on X-Axis at 1, 3, 5, 7, 9, and 11.
  • Label the X-Axis ticks as January, March, May, July, September, and November respectively.
  • Label X-Axis as Months
  • Label Y-Axis as No. of Cars Sold
  • Set Title as "Cars Sold by Company 'Z' in 2021".
  • Add a legend.
  • return the figure object

Note: The results of preliminary validation doesn't impact final scoring. In-depth scorings are done at a later stage.

Once you are in the Web IDE:

  1. Open prog.py in the jupyter lab the file and start your coding by following the instructions given above.
  2. Once you are done with the solution , then run the following commands in the terminal to check your solutions. Click File -> New -> Terminal, run the following commands

    python3 prog.py
    
  3. After running the test cases, click the submit button and click on Submit Test to end the assessment.

Note - Here Rough_Work.ipynb can be used for rough work to get the solutions

Solution

import numpy as np
import matplotlib.pyplot as plt


def sine_wave_plot():

    # Write your functionality below
    fig = plt.figure(figsize=(13, 4))
    ax = fig.add_subplot(111)
    arr_t = np.linspace(0.0, 3.0, num = 250)
    arr_v = np.sin(2.5 * np.pi * arr_t)
    ax.plot(arr_t, arr_v, label="sin(arr_t)")
    ax.set_xlabel("Time (seconds)")
    ax.set_ylabel("Voltage (mv)")
    ax.set_title("Sine Wave")
    ax.set_xlim(0, 2)
    ax.set_ylim(-1, 1)
    ax.set_xticks([0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0])
    ax.set_yticks([-1, 0, 1])
    ax.grid(linestyle="dashdot")
    ax.legend(["Voltage Speed"])
    return fig


def multi_curve_plot():

    # Write your functionality below
    fig = plt.figure(figsize=(13, 4))
    ax = fig.add_subplot(111)
    arr_x = np.linspace(0.0, 7.0, num = 25)
    arr_y1 = arr_x
    arr_y2 = arr_x ** 2
    arr_y3 = arr_x ** 3

    ax.plot(arr_x, arr_y1, color="green", marker="^", label ="y = arr_x")
    ax.plot(arr_x, arr_y2, color="blue", marker="s", label ="y = arr_x**2")
    ax.plot(arr_x, arr_y3, color="red", marker="o", label ="y = arr_x**3")
    ax.set_xlabel("arr_x")
    ax.set_ylabel("f(arr_x)")
    ax.set_title("Linear, Quadratic, & Cubic Equations")
    ax.legend(["Linear", "Quadratic", "Cubic"])
    return fig



def scatter_plot():

    # Write your functionality below
    fig = plt.figure(figsize=(13, 4))
    ax = fig.add_subplot(111)
    car_sales = [40, 65, 70, 40, 55, 60, 75, 60, 80, 95, 96, 105]
    months = np.array(range(1, 13))
    ax.scatter(months, car_sales, color="green", label="car sales")
    ax.set_xlim(0, 13)
    ax.set_ylim(10, 110)
    ax.set_xticks(np.array(range(1, 13, 2)), ["January", "March", "May", "July", "September", "November"])
    ax.set_xlabel("Months")
    ax.set_ylabel("No. of Cars Sold")
    ax.set_title("Cars Sold by Company 'Z' in 2021")
    ax.legend(["Count of Cars Sold"])
    return fig


# Note: Do Not modify the below code
if __name__ == '__main__':
    import sys
    import subprocess
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'test_plot2-0.1-py3-none-any.whl'], stdout=subprocess.DEVNULL)
    from test_plot2 import matplotlib2
    usr_fig1 = sine_wave_plot()
    usr_fig2 = multi_curve_plot()
    usr_fig3 = scatter_plot()
    matplotlib2.save_answer(usr_fig1, usr_fig2, usr_fig3)

Matplotlib-3 - Bar Plots

Task1

  • Create a function named barplot_of_iris_sepal_length.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Define a list species, with elements ['setosa', 'versicolor', 'virginica'].
  • Define a list index, with values [0.4, 1.4, 2.4].
  • Define another list sepal_len with values [6.01, 6.94, 7.69]. These values represent the mean sepal length of iris flowers belonging to three species.
  • Draw a bar plot using the bar function, such that the height of each vertical bar displays the sepal length of a species label it as Sepal Length.
  • Use index and sepal_len as variables. Set bar width as 0.4, color as blue, and border color of the bar as red.
  • Label X-Axis as Species.
  • Label Y-Axis as Sepal Length (cm).
  • Set Title as Mean Sepal Length of Iris Species.
  • Limit X-Axis from 0 to 3.
  • Limit Y-Axis from 0 to 9.
  • Set ticks on X-Axis at 0.4, 1.4, and 2.4.
  • Set X-Axis tick labels to ['setosa', 'versicolor', 'virginica'].
  • Add a legend.
  • return the figure object.

Task2

  • Create a function named barplot_of_iris_measurements.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Define the following lists:
  • sepal_len = [6.01, 6.94, 7.59]
  • sepal_wd = [4.42, 3.77, 3.97]
  • petal_len = [2.46, 5.26, 6.55]
  • petal_wd = [1.24, 2.33, 3.03]
  • species = ['setosa', 'versicolor', 'virginica']
  • species_index1 = [0.7, 1.7, 2.7]
  • species_index2 = [0.9, 1.9, 2.9]
  • species_index3 = [1.1, 2.1, 3.1]
  • species_index4 = [1.3, 2.3, 3.3]
  • Draw vertical bars showing the mean sepal length of a species. Set the color of the bars to m, boundary line color to grey, width of bars as 0.2, and label it as Sepal Length. Use bar with species_index1 and sepal_len.
  • Draw vertical bars showing mean sepal length of a species. Set the color of the bars to y, boundary line color to grey, width of bars as 0.2, and label it as Sepal Width. Use bar with species_index2 and sepal_wd.
  • Draw vertical bars showing mean sepal length of a species. Set the color of the bars to c, boundary line color to grey, width of bars as 0.2, and label it as Petal Length. Use bar with species_index3 and petal_len.
  • Draw vertical bars showing mean sepal length of a species. Set the color of the bars to orange, boundary line color to grey, width of bars as 0.2, and label it as Petal Width. Use bar with species_index4 and petal_wd.
  • Label X-Axis as Species.
  • Label Y-Axis as Iris Measurements (cm).
  • Set Title as Mean Measurements of Iris Species.
  • Limit X-Axis from 0.5 to 3.5 .
  • Limit Y-Axis from 0 to 10.
  • Mark major ticks on X-Axis at 1.0, 2.0, and 3.0.
  • Label the major ticks on X-Axis as setosa, versicolor and virginica respectively.
  • Add a legend.
  • return the figure object.

Task3

  • Create a function named hbarplot_of_iris_petal_length.
  • Create a figure of size 15 inches in width, and 5 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Define a list species, with elements ['setosa', 'versicolor', 'virginica'].
  • Define a list index, with values [0.1, 1.1, 2.1].
  • Define another list petal_len with values [2.67, 5.49, 6.37]. These values represent the mean petal length of iris flowers belonging to three species.
  • Draw a horizontal bar plot using barh function, such that the width of each bar display the petal length of a species and label it as Petal Length.
  • Use index and petal_len as variables. Set bar height as 0.4, color as m, and border color of the bar as c.
  • Label Y-Axis as Species
  • Label X-Axis as `Petal Length (cm).
  • Set Title as Mean Petal Length of Iris Species.
  • Mark major ticks on Y-Axis at 0.10, 1.10 and 2.10.
  • Label the major ticks on Y-Axis as setosa, versicolor and virginica respectively.
  • Add a legend.
  • return the figure object.

Note: The results of preliminary validation doesn't impact final scoring. In-depth scorings are done at a later stage.

Once you are in the Web IDE:

  1. Open prog.py in the jupyter lab the file and start your coding by following the instructions given above.
  2. Once you are done with the solution , then run the following commands in the terminal to check your solutions. Click File -> New -> Terminal, run the following commands

    python3 prog.py
    
  3. After running the test cases, click the submit button and click on Submit Test to end the assessment.

Note - Here Rough_Work.ipynb can be used for rough work to get the solutions

Solution

import numpy as np
import matplotlib.pyplot as plt


def barplot_of_iris_sepal_length():

    # Write your functionality below
    fig = plt.figure(figsize=(9, 7))
    ax = fig.add_subplot(111)
    species = ['setosa', 'versicolor', 'virginica']
    index = [0.4, 1.4, 2.4]
    sepal_len = [6.01, 6.94, 7.69]
    ax.bar(index, sepal_len, label="Sepal Length", width=0.4, color="blue", edgecolor="red")
    ax.set_xlabel("Species")
    ax.set_ylabel("Sepal Length (cm)")
    ax.set_title("Mean Sepal Length of Iris Species")
    ax.set_xlim(0, 3)
    ax.set_ylim(0, 9)
    ax.set_xticks(index)
    ax.set_xticklabels(species)
    ax.legend(["Sepal Length"])
    return fig


def barplot_of_iris_measurements():

    # Write your functionality below
    fig = plt.figure(figsize=(9, 7))
    ax = fig.add_subplot(111)
    sepal_len = [6.01, 6.94, 7.59]
    sepal_wd = [4.42, 3.77, 3.97]
    petal_len = [2.46, 5.26, 6.55]
    petal_wd = [1.24, 2.33, 3.03]
    species = ['setosa', 'versicolor', 'virginica']
    species_index1 = [0.7, 1.7, 2.7]
    species_index2 = [0.9, 1.9, 2.9]
    species_index3 = [1.1, 2.1, 3.1]
    species_index4 = [1.3, 2.3, 3.3]

    ax.bar(species_index1, sepal_len, color="m", edgecolor="grey", width=0.2, label="Sepal Length")
    ax.bar(species_index2, sepal_wd, color="y", edgecolor="grey", width=0.2, label="Sepal Width")
    ax.bar(species_index3, petal_len, color="c", edgecolor="grey", width=0.2, label="Petal Length")
    ax.bar(species_index4, petal_wd, color="orange", edgecolor="grey", width=0.2, label="Petal Width")
    ax.set_xlabel("Species")
    ax.set_ylabel("Iris Measurements (cm)")
    ax.set_title("Mean Measurements of Iris Species")
    ax.set_xlim(0.5, 3.5)
    ax.set_ylim(0, 10)
    ax.set_xticks([1.0, 2.0, 3.0])
    ax.set_xticklabels(species)
    ax.legend(["Sepal Length", "Sepal Width", "Petal Length", "Petal Width"])

    return fig


def hbarplot_of_iris_petal_length():

    # Write your functionality below
    fig = plt.figure(figsize=(15, 5))
    ax = fig.add_subplot(111)
    species = ['setosa', 'versicolor', 'virginica']
    index = [0.1, 1.1, 2.1]
    petal_len = [2.67, 5.49, 6.37]

    ax.barh(index, petal_len, height=0.4, label="Petal Length", color="m", edgecolor="c")
    ax.set_xlabel("Species")
    ax.set_ylabel("Petal Length (cm)")
    ax.set_title("Mean Petal Length of Iris Species")
    ax.set_yticks(index)
    ax.set_yticklabels(species)
    ax.legend(["Petal Length"])

    return fig


# Note: Do Not modify the below code
if __name__ == '__main__':
    import sys
    import subprocess
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'test_plot3-0.1-py3-none-any.whl'], stdout=subprocess.DEVNULL)
    from test_plot3 import matplotlib3
    usr_fig1 = barplot_of_iris_sepal_length()
    usr_fig2 = barplot_of_iris_measurements()
    usr_fig3 = hbarplot_of_iris_petal_length()
    matplotlib3.save_answer(usr_fig1, usr_fig2, usr_fig3)

Matplotlib-4 - Histograms and Box Plots

Task1

  • Create a function named hist_of_a_sample_normal_distribution.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Set random seed to 100 using the expression np.random.seed(100).
  • Create a normal distribution dist_arr of 1000 values, with mean 35 and standard deviation 3.0. Use np.random.randn.
  • Draw a histogram of dist_arr with 35 bins. Use the hist function.
  • Label X-Axis as dist_arr
  • Label Y-Axis as Bin Count
  • Set Title as Histogram of a Single Dataset
  • return the figure object.

Task2

  • Create a function named boxplot_of_four_normal_distribution.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Set random seed to 100 using the expression np.random.seed(100).
  • Create a normal distribution arr_1 of 2000 values, with mean 35 and standard deviation 6.0. Use np.random.randn.
  • Create a normal distribution arr_2 of 2000 values, with mean 25 and standard deviation 4.0. Use np.random.randn.
  • Create a normal distribution arr_3 of 2000 values, with mean 45 and standard deviation 8.0. Use np.random.randn.
  • Create a normal distribution arr_4 of 2000 values, with mean 55 and standard deviation 10.0. Use np.random.randn.
  • Create a list labels with elements ['arr_1', 'arr_2', 'arr_3', 'arr_4].
  • Draw a Boxplot arr_1, arr_2, arr_3, arr_4 with notches and label it using the labels list. Use the boxplot function.
  • Choose o symbol for outlier, and fill color inside boxes by setting patch_artist argument to True.
  • Label X-Axis as Dataset
  • Label Y-Axis as Value
  • Set Title as Box plot of Multiple Datasets
  • return the figure object.

Note: The results of preliminary validation doesn't impact final scoring. In-depth scorings are done at a later stage.

Once you are in the Web IDE:

  1. Open prog.py in the jupyter lab the file and start your coding by following the instructions given above.
  2. Once you are done with the solution , then run the following commands in the terminal to check your solutions. Click File -> New -> Terminal, run the following commands

    python3 prog.py
    
  3. After running the test cases, click the submit button and click on Submit Test to end the assessment.

Note - Here Rough_Work.ipynb can be used for rough work to get the solutions

Solution

import numpy as np
import matplotlib.pyplot as plt


def hist_of_a_sample_normal_distribution():

    # Write your functionality below
    fig = plt.figure(figsize=(9,7))
    ax = fig.add_subplot(111)
    np.random.seed(100)
    dist_arr = np.random.randn(1000) * 3.0 + 35
    ax.hist(dist_arr, bins=35)
    ax.set_xlabel("dist_arr")
    ax.set_ylabel("Bin Count")
    ax.set_title("Histogram of a Single Dataset")
    return fig


def boxplot_of_four_normal_distribution():

    # Write your functionality below
    fig = plt.figure(figsize=(9,7))
    ax = fig.add_subplot(111)
    np.random.seed(100)
    arr_1 = np.random.randn(2000) * 6.0 + 35
    arr_2 = np.random.randn(2000) * 4.0 + 25
    arr_3 = np.random.randn(2000) * 8.0 + 45
    arr_4 = np.random.randn(2000) * 10.0 + 55
    elements = ['arr_1', 'arr_2', 'arr_3', 'arr_4']
    ax.boxplot([arr_1, arr_2, arr_3, arr_4], labels=elements, patch_artist=True, sym='o')
    ax.set_xlabel("Dataset")
    ax.set_ylabel("Value")
    ax.set_title("Box plot of Multiple Datasets")
    return fig


# Note: Do Not modify the below code
if __name__ == '__main__':
    import sys
    import subprocess
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'test_plot4-0.1-py3-none-any.whl'], stdout=subprocess.DEVNULL)
    from test_plot4 import matplotlib4
    usr_fig1 = hist_of_a_sample_normal_distribution()
    usr_fig2 = boxplot_of_four_normal_distribution()
    matplotlib4.save_answer(usr_fig1, usr_fig2)

Matplotlib-5 - Applying Styles

Task1

  • Create a function named generate_plot_with_style1.
  • Generate the following barplot with 'ggplot' style. Use 'with' to apply the style to the code generating the barplot.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Create an axis, associated with figure fig, using add_subplot. Name it as ax.
  • Define the following lists
  • sepal_len = [6.01, 6.94, 7.59]
  • sepal_wd = [4.42, 3.77, 3.97]
  • petal_len = [2.46, 5.26, 6.55]
  • petal_wd = [1.24, 2.33, 3.03]
  • species = ['setosa', 'versicolor', 'virginica']
  • species_index1 = [0.8, 1.8, 2.8]
  • species_index2 = [1.0, 2.0, 3.0]
  • species_index3 = [1.2, 2.2, 3.2]
  • species_index4 = [1.4, 2.4, 3.4]
  • Draw vertical bars showing mean sepal length of a species. Set width of the bars as 0.2, and label it as Sepal Length. Use bar with species_index1 and sepal_len.
  • Draw vertical bars showing mean sepal length of a species. Set width of bars as 0.2 and label it as Sepal Width. Use bar with species_index2 and sepal_wd.
  • Draw vertical bars showing mean sepal length of a species. Set width of bars as 0.2 and label it as Petal Length. Use bar with species_index3 and petal_len.
  • Draw vertical bars showing mean sepal length of a species. Set width of bars as 0.2 and label it as Petal Width. Use bar with species_index4 and petal_wd.
  • Label X-Axis as Species.
  • Label Y-Axis as Iris Measurements (cm).
  • Set Title as Mean Measurements of Iris Species.
  • Limit X-Axis from 0.5 to 3.7.
  • Limit Y-Axis from 0 to 10.
  • Mark major ticks on X-Axis at 1.0, 2.0, and 3.0.
  • Label the major ticks on X-Axis as setosa, versicolor, and virginica respectively.
  • Add a legend.
  • return the figure object.

Task2

  • Create a function named generate_plot_with_style2.
  • Regenerate the barplot defined in 'generate_plot_with_style1' using 'seaborn-colorblind' style. Use 'with' for applying the style.
  • Limit X-Axis from 0.5 to 3.5.
  • return the figure object.

Task3

  • Create a function named generate_plot_with_style3.
  • Regenerate the barplot defined in 'generate_plot_with_style1' using 'grayscale' style. Use 'with' for applying the style.
  • Limit X-Axis from 0.5 to 3.5.
  • return the figure object.

Note: The results of preliminary validation doesn't impact final scoring. In-depth scorings are done at a later stage.

Once you are in the Web IDE:

  1. Open prog.py in the jupyter lab the file and start your coding by following the instructions given above.
  2. Once you are done with the solution , then run the following commands in the terminal to check your solutions. Click File -> New -> Terminal, run the following commands

    python3 prog.py
    
  3. After running the test cases, click the submit button and click on Submit Test to end the assessment.

Note - Here Rough_Work.ipynb can be used for rough work to get the solutions

Solution

import numpy as np
import matplotlib.pyplot as plt


def generate_plot_with_style1():

    # Write your functionality below
    fig = None
    sepal_len = [6.01, 6.94, 7.59]
    sepal_wd = [4.42, 3.77, 3.97]
    petal_len = [2.46, 5.26, 6.55]
    petal_wd = [1.24, 2.33, 3.03]
    species = ['setosa', 'versicolor', 'virginica']
    species_index1 = [0.8, 1.8, 2.8]
    species_index2 = [1.0, 2.0, 3.0]
    species_index3 = [1.2, 2.2, 3.2]
    species_index4 = [1.4, 2.4, 3.4]
    with plt.style.context('ggplot'):
        fig = plt.figure(figsize=(9, 7))
        ax = fig.add_subplot(111)
        ax.set(title="Mean Measurements of Iris Species", xlabel="Species", ylabel="Iris Measurements (cm)")
        ax.bar(species_index1, sepal_len, width=0.2, label="Sepal Length")
        ax.bar(species_index2, sepal_wd, width=0.2, label="Sepal Width")
        ax.bar(species_index3, petal_len, width=0.2, label="Petal Length")
        ax.bar(species_index4, petal_wd, width=0.2, label="Petal Width")
        ax.set_xlim(0.5, 3.7)
        ax.set_ylim(0, 10)
        ax.set_xticks([1.0, 2.0, 3.0])
        ax.set_xticklabels(species)
        ax.legend(["Sepal Length", "Sepal Width", "Petal Length", "Petal Width"])
    return fig


def generate_plot_with_style2():

    # Write your functionality below
    fig = None
    sepal_len = [6.01, 6.94, 7.59]
    sepal_wd = [4.42, 3.77, 3.97]
    petal_len = [2.46, 5.26, 6.55]
    petal_wd = [1.24, 2.33, 3.03]
    species = ['setosa', 'versicolor', 'virginica']
    species_index1 = [0.8, 1.8, 2.8]
    species_index2 = [1.0, 2.0, 3.0]
    species_index3 = [1.2, 2.2, 3.2]
    species_index4 = [1.4, 2.4, 3.4]
    with plt.style.context('seaborn-colorblind'):
        fig = plt.figure(figsize=(9, 7))
        ax = fig.add_subplot(111)
        ax.set(title="Mean Measurements of Iris Species", xlabel="Species", ylabel="Iris Measurements (cm)")
        ax.bar(species_index1, sepal_len, width=0.2, label="Sepal Length")
        ax.bar(species_index2, sepal_wd, width=0.2, label="Sepal Width")
        ax.bar(species_index3, petal_len, width=0.2, label="Petal Length")
        ax.bar(species_index4, petal_wd, width=0.2, label="Petal Width")
        ax.set_xlim(0.5, 3.5)
        ax.set_ylim(0, 10)
        ax.set_xticks([1.0, 2.0, 3.0])
        ax.set_xticklabels(species)
        ax.legend(["Sepal Length", "Sepal Width", "Petal Length", "Petal Width"])

    return fig


def generate_plot_with_style3():

    # Write your functionality below
    fig = None
    sepal_len = [6.01, 6.94, 7.59]
    sepal_wd = [4.42, 3.77, 3.97]
    petal_len = [2.46, 5.26, 6.55]
    petal_wd = [1.24, 2.33, 3.03]
    species = ['setosa', 'versicolor', 'virginica']
    species_index1 = [0.8, 1.8, 2.8]
    species_index2 = [1.0, 2.0, 3.0]
    species_index3 = [1.2, 2.2, 3.2]
    species_index4 = [1.4, 2.4, 3.4]
    with plt.style.context('grayscale'):
        fig = plt.figure(figsize=(9, 7))
        ax = fig.add_subplot(111)
        ax.set(title="Mean Measurements of Iris Species", xlabel="Species", ylabel="Iris Measurements (cm)")
        ax.bar(species_index1, sepal_len, width=0.2, label="Sepal Length")
        ax.bar(species_index2, sepal_wd, width=0.2, label="Sepal Width")
        ax.bar(species_index3, petal_len, width=0.2, label="Petal Length")
        ax.bar(species_index4, petal_wd, width=0.2, label="Petal Width")
        ax.set_xlim(0.5, 3.5)
        ax.set_ylim(0, 10)
        ax.set_xticks([1.0, 2.0, 3.0])
        ax.set_xticklabels(species)
        ax.legend(["Sepal Length", "Sepal Width", "Petal Length", "Petal Width"])

    return fig


# Note: Do Not modify the below code
if __name__ == '__main__':
    import sys
    import subprocess
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'test_plot5-0.1-py3-none-any.whl'], stdout=subprocess.DEVNULL)
    from test_plot5 import matplotlib5
    usr_fig1 = generate_plot_with_style1()
    usr_fig2 = generate_plot_with_style2()
    usr_fig3 = generate_plot_with_style3()
    matplotlib5.save_answer(usr_fig1, usr_fig2, usr_fig3)

Matplotlib-6 - Multiple Plots

Task1

  • Create a function named generate_figure1.
  • Define a numpy array 'x' with expression 'np.arange(0.0, 10.0, 0.01)'.
  • Define another numpy array 'arr_s1' with expression 'np.sin(3*np.pi*x)'
  • Define one more numpy array 'arr_s2' with expression 'np.sin(6*np.pi*x)'.
  • Create a figure of size 12 inches in width, and 7 inches in height. Name it as fig.
  • Create an axes, using plt.subplot function. Name it as axes1. The subplot must point to the first virtual grid created by 2 rows and 1 column. Set 'title' argument to 'Sin(3*pi*x)'.
  • Draw a line plot of 'x' and 'arr_s1' using the 'plot' function on 'axes1`.
  • Create another axes, using the plt.subplot function. Name it as axes2. The subplot must point to the second virtual grid created by 2 rows and 1 column. Set 'title' argument to 'Sin(6*pi*x)'. Set 'sharex' argument to 'axes1' and 'sharey' argument to 'axes1'.
  • Draw a line plot of 'x' and 'arr_s2' using the 'plot' function on 'axes2`.
  • return the figure object

Task2

  • Create a function named generate_figure2.
  • Set random seed to 1500 using the expression 'np.random.seed(1500)'.
  • Define a numpy array 'x' with expression 'np.random.rand(10)'.
  • Define another numpy array 'y' with expression 'np.random.rand(10)'.
  • Define one more numpy array 'z' with expression 'np.sqrt(x**2 + y**2)'.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Create an axes, using plt.subplot function. Name it as axes1. The subplot must point to the first virtual grid created by 2 rows and 2 columns. Set 'title' argument to 'Scatter plot with Diamond Markers'.
  • Draw a scatter plot of 'x' and 'y' using 'scatter' function on 'axes1`. Set argument 's' to 80, 'c' to z and 'marker' to 'd'.
  • Add ticks on X-Axis at 0.0, 0.5, 1.0, 1.5 and ticks on Y-Axis at -0.2, 0.2, 0.6, 1.0 respectively
  • Create an axes, using plt.subplot function. Name it as axes2. The subplot must point to the Second virtual grid created by 2 rows and 2 columns. Set 'title' argument to 'Scatter plot with Circle Markers'.
  • Draw a scatter plot of 'x' and 'y' using 'scatter' function on 'axes2`. Set argument 's' to 80, 'c' to 'z' and 'marker' to 'o'.
  • Add ticks on X-Axis at 0.0, 0.5, 1.0, 1.5 and ticks on Y-Axis at -0.2, 0.2, 0.6, 1.0 respectively.
  • Create an axes, using plt.subplot function. Name it as axes3. The subplot must point to the Third virtual grid created by 2 rows and 2 columns. Set 'title' argument to 'Scatter plot with Plus Markers'.
  • Draw a scatter plot of 'x' and 'y' using 'scatter' function on 'axes3`. Set argument 's' to 80, 'c' to 'z' and 'marker' to '+'.
  • Add ticks on X-Axis at 0.0, 0.5, 1.0, 1.5 and ticks on Y-Axis at -0.2, 0.2, 0.6, 1.0 respectively.
  • Create an axes, using plt.subplot function. Name it as axes4. The subplot must point to the Fourth virtual grid created by 2 rows and 2 columns. Set 'title' argument to 'Scatter plot with Upper Triangle Markers'.
  • Draw a scatter plot of 'x' and 'y' using 'scatter' function on 'axes4`. Set argument 's' to 80, 'c' to 'z' and 'marker' to '^'.
  • Add ticks on X-Axis at 0.0, 0.5, 1.0, 1.5 and ticks on Y-Axis at -0.2, 0.2, 0.6, 1.0 respectively
  • Adjust the entire layout with expression 'plt.tight_layout()'.
  • return the figure object

Task3

  • Create a function named generate_figure3.
  • Define a numpy array 'x' with expression 'np.arange(1, 301, 3)'.
  • Define another numpy array 'y1' with expression 'y1 = x'.
  • Define another numpy array 'y2' with expression 'y2 = x**2'.
  • Define another numpy array 'y3' with expression 'y3 = x**3'.
  • Create a figure of size 9 inches in width, and 7 inches in height. Name it as fig.
  • Define a grid 'gr' of 2 rows and 2 columns, using 'GridSpec' function. Ensure that 'matplotlib.gridspec' is imported, before defining the grid.
  • Create an axes, using plt.subplot function. Name it as axes1. The subplot must span the 1st row and 1st column of the defined grid 'gr'. Set 'title' argument to 'y = x'.
  • Draw a line plot of 'x' and 'y1' using 'plot' function on 'axes1`.
  • Create an axes, using plt.subplot function. Name it as axes2. The subplot must span 2nd row and 1st column of defined grid 'gr'. Set 'title' argument to 'y = x**2'.
  • Draw a line plot of 'x' and 'y2' using 'plot' function on 'axes2`.
  • Create an axes, using plt.subplot function. Name it as axes3. The subplot must span all rows of 2nd column of defined grid 'gr'. Set 'title' argument to 'y = x**3'.
  • Draw a line plot of 'x' and 'y3' using 'plot' function on 'axes3`.
  • Adjust the entire layout with the expression 'plt.tight_layout()'.
  • return the figure object

Note: The results of preliminary validation doesn't impact final scoring. In-depth scorings are done at a later stage.

Once you are in the Web IDE:

  1. Open prog.py in the jupyter lab the file and start your coding by following the instructions given above.
  2. Once you are done with the solution , then run the following commands in the terminal to check your solutions. Click File -> New -> Terminal, run the following commands

    python3 prog.py
    
  3. After running the test cases, click the submit button and click on Submit Test to end the assessment.

Note - Here Rough_Work.ipynb can be used for rough work to get the solutions

Solution

import numpy as np
import matplotlib.pyplot as plt


def generate_figure1():

    # Write your functionality below
    fig = plt.figure(figsize=(12, 7))
    x = np.arange(0.0, 10.0, 0.01)
    arr_s1 = np.sin(3 * np.pi * x)
    arr_s2 = np.sin(6 * np.pi * x)

    axes1 = plt.subplot(2,1,1,title="Sin(3*pi*x)")
    axes1.plot(x, arr_s1)

    axes2 = plt.subplot(2,1,2,title="Sin(6*pi*x)")
    axes2.plot(x, arr_s2)
    return fig


def generate_figure2():

    # Write your functionality below
    fig = plt.figure(figsize=(9, 7))
    np.random.seed(1500)
    x = np.random.rand(10)
    y = np.random.rand(10)
    z = np.sqrt(x**2 + y**2)

    axes1 = plt.subplot(2, 2, 1, title="Scatter plot with Diamond Markers")
    axes1.scatter(x, y, s=80, c=z, marker='d')
    axes1.set_xticks([0.0, 0.5, 1.0, 1.5])
    axes1.set_yticks([-0.2, 0.2, 0.6, 1.0])

    axes2 = plt.subplot(2, 2, 2, title="Scatter plot with Circle Markers")
    axes2.scatter(x, y, s=80, c=z, marker='o')
    axes2.set_xticks([0.0, 0.5, 1.0, 1.5])
    axes2.set_yticks([-0.2, 0.2, 0.6, 1.0])

    axes3 = plt.subplot(2, 2, 3, title="Scatter plot with Plus Markers")
    axes3.scatter(x, y, s=80, c=z, marker='+')
    axes3.set_xticks([0.0, 0.5, 1.0, 1.5])
    axes3.set_yticks([-0.2, 0.2, 0.6, 1.0])

    axes4 = plt.subplot(2, 2, 4, title="Scatter plot with Upper Triangle Markers")
    axes4.scatter(x, y, s=80, c=z, marker='^')
    axes4.set_xticks([0.0, 0.5, 1.0, 1.5])
    axes4.set_yticks([-0.2, 0.2, 0.6, 1.0])

    plt.tight_layout()
    return fig


def generate_figure3():
    import matplotlib.gridspec as gridspec
    # Write your functionality below
    x = np.arange(1, 301, 3)
    y1 = x
    y2 = x**2
    y3 = x**3

    fig = plt.figure(figsize=(9, 7))
    gr = gridspec.GridSpec(2,2)

    axes1 = plt.subplot(gr[0,0], title='y = x')
    axes1.plot(x, y1)

    axes2 = plt.subplot(gr[1,0], title="y = x**2")
    axes2.plot(x, y2)

    axes3 = plt.subplot(gr[:,1], title="y = x**3")
    axes3.plot(x, y3)

    plt.tight_layout()
    return fig


# Note: Do Not modify the below code
if __name__ == '__main__':
    import sys
    import subprocess
    subprocess.check_call(
        [sys.executable, "-m", "pip", "install", 'test_plot6-0.2-py3-none-any.whl'], stdout=subprocess.DEVNULL)
    from test_plot6 import matplotlib6
    usr_fig1 = generate_figure1()
    usr_fig2 = generate_figure2()
    usr_fig3 = generate_figure3()
    matplotlib6.save_answer(usr_fig1, usr_fig2, usr_fig3)
Share: