Computer Science Project || ISC || Sunrise Days

Problem 1: Write a program to check a number is Smith or not. [Digits of Smith number when added is equal to sum of digits of prime factors of the number. 27 is Smith number because 2+7=9 and 27=333]

Solution

import java.util.Scanner;

class Smith {
    public static boolean isPrime(int n) {
        if (n <= 1)
            return false;
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }

    public static int sumOfDigit(int n) {
        int sum = 0;
        while (n > 0) {
            sum = sum + n % 10;
            n = n / 10;
        }
        return sum;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = sc.nextInt();
        int k=n, s=0;
        for (int i = 2; i <= n; i++) {
            if (isPrime(i)) {
                while (k % i == 0) {
                    k = k / i;
                    s = s + sumOfDigit(i);
                }
            }
        }
        if (sumOfDigit(n) == s)
            System.out.println(n + " is Smith number");
        else
            System.out.println(n + " is not Smith number");
        sc.close();
    }
}

Output

Enter a number:
27
27 is Smith number

Enter a number:
12
12 is not Smith number

Problem 2: Write a program to check whether a number is Kaprekar. [A Kaprekar number's square can be split into two parts that add up to the original number. 45 is Kaprekar number because 45^2 = 2025 and 20+25=45].

Solution

import java.util.Scanner;

class Kaprekar {
    public static int noOfDigits(int n) {
        int count = 0;
        while (n > 0) {
            count++;
            n = n / 10;
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = sc.nextInt();
        int c = noOfDigits(n);
        int sq = n * n;
        int l = sq / (int) Math.pow(10, c);
        int r = sq % (int) Math.pow(10, c);
        if (l + r == n)
            System.out.println(n + " is Kaprekar number");
        else
            System.out.println(n + " is not Kaprekar number");
        sc.close();
    }
}

Output

Enter a number:
45
45 is Kaprekar number

Enter a number:
10
10 is not Kaprekar number

Problem 3: Write a program to find out the given number is a ISBN number or not. [ISBN is a 10 digit number where the last digit is a check digit. The check digit is calculated as (10a1+9a2+8a3+7a4+6a5+5a6+4a7+3a8+2*a9)%11 and if the check digit is 10 then it is represented as X]

Solution

import java.util.Scanner;

class ISBN {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = sc.nextInt();
        int sum = 0;
        int a = n;
        int i = 10;
        while (a > 0) {
            int r = a % 10;
            sum = sum + r * i;
            a = a / 10;
            i--;
        }
        int checkDigit = sum % 11;
        if (checkDigit == 10)
            System.out.println(n + " is ISBN number");
        else
            System.out.println(n + " is not ISBN number");
        sc.close();
    }
}

Output

Enter a number:
950126105537
950126105537 is ISBN number

Enter a number:
950126105538
950126105538 is not ISBN number

Problem 4: Write a program to check whether a number is Disarium. [A Disarium number is a number where the sum of its digits powered with their respective positions is equal to the number itself. 175 is Disarium number because 1^1+7^2+5^3=175]

Solution

import java.util.Scanner;

class Disarium {
    public static int noOfDigits(int n) {
        int count = 0;
        while (n > 0) {
            count++;
            n = n / 10;
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = sc.nextInt();
        int c = noOfDigits(n);
        int sum = 0;
        int a = n;
        int i = 1;
        while (a > 0) {
            int r = a % 10;
            sum = sum + (int) Math.pow(r, i);
            a = a / 10;
            i++;
        }
        if (sum == n)
            System.out.println(n + " is Disarium number");
        else
            System.out.println(n + " is not Disarium number");
        sc.close();
    }
}

Output

Enter a number:
175
175 is Disarium number

Enter a number:
176
176 is not Disarium number

Problem 5: Write a program to check whether a number is Keith. [A Keith number isis a number that appears in a sequence generated from its own digits, where the sequence starts with the digits of the number, and each new term is the sum of the previous k terms (k being the number of digits). For example, 197 (3 digits) starts a sequence: 1, 9, 7, (1+9+7)=17, (9+7+17)=33, (7+17+33)=57, (17+33+57)=107, (33+57+107)=197; since 197 appears, it's a Keith number.]

Solution

import java.util.Scanner;

class Keith {
    public static int noOfDigits(int n) {
        int count = 0;
        while (n > 0) {
            count++;
            n = n / 10;
        }
        return count;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = sc.nextInt();
        int c = noOfDigits(n);
        int[] arr = new int[c];
        int a = n;
        int i = 0;
        while (a > 0) {
            arr[i] = a % 10;
            a = a / 10;
            i++;
        }
        int sum = 0;
        for (int j = 0; j < c; j++) {
            sum = sum + arr[j];
        }
        while (sum != n) {
            for (int j = 0; j < c - 1; j++) {
                arr[j] = arr[j + 1];
            }
            arr[c - 1] = sum;
            sum = 0;
            for (int j = 0; j < c; j++) {
                sum = sum + arr[j];
            }
        }
        if (sum == n)
            System.out.println(n + " is Keith number");
        else
            System.out.println(n + " is not Keith number");
        sc.close();
    }
}

Output

Enter a number:
197
197 is Keith number

Enter a number:
198
198 is not Keith number

Problem 6: Write a program to generate a Pascal Triangle for n rows. [Pascal's Triangle is a triangular array of the binomial coefficients. The rows of Pascal's Triangle are conventionally enumerated starting with row 0 at the top.]

Solution

import java.util.Scanner;

class PascalTriangle {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the number of rows: ");
        int n = sc.nextInt();
        int[][] arr = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j <= i; j++) {
                if (j == 0 || j == i)
                    arr[i][j] = 1;
                else
                    arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j];
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n - i - 1; j++) {
                System.out.print(" ");
            }
            for (int j = 0; j <= i; j++) {
                System.out.print(arr[i][j] + " ");
            }
            System.out.println();
        }
        sc.close();
    }
}

Output

Enter the number of rows:
5
    1
   1 1
  1 2 1
 1 3 3 1
1 4 6 4 1

Problem 7: Write a program to find GCD using recursive function. [GCD is the greatest common divisor of two numbers. It is the largest number that divides both numbers without leaving a remainder.]

Solution

import java.util.Scanner;

class GCD {
    public static int gcd(int a, int b) {
        if (b == 0)
            return a;
        else
            return gcd(b, a % b);
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter two numbers: ");
        int a = sc.nextInt();
        int b = sc.nextInt();
        System.out.println("GCD of " + a + " and " + b + " is " + gcd(a, b));
        sc.close();
    }
}

Output

Enter two numbers:
48 18
GCD of 48 and 18 is 6

Problem 8: Write a program to perform Permutation for a given limit and a common factor. [Permutation is an arrangement of all the members of a set into some sequence or order.]

Solution

import java.util.Scanner;

class Permutation {
    public static long fact(int n) {
        if (n == 0)
            return 1;
        else
            return n * fact(n - 1);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the limit: ");
        int n = sc.nextInt();
        System.out.println("Enter the common factor: ");
        int r = sc.nextInt();
        long count = fact(n) / fact(n - r); // n! / (n-k)!)
        System.out.println("Number of permutations where product is divisible by " + r + " is " + count);
        sc.close();
    }
}

Output

Enter the limit:
12
Enter the common factor:
4
Number of permutations where product is divisible by 4 is 11880

Problem 9: Write a program to perform combination for a given limit and a common factor. [Combination is a selection of items from a larger set, where the order of selection does not matter.]

Solution

import java.util.Scanner;

class Combination {
    public static long fact(int n) {
        if (n == 0)
            return 1;
        else
            return n * fact(n - 1);
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the limit: ");
        int n = sc.nextInt();
        System.out.println("Enter the common factor: ");
        int r = sc.nextInt();
        long count = fact(n) / (fact(r) * fact(n - r)); // n! / (r! * (n-r)!)
        System.out.println("Number of combinations where product is divisible by " + r + " is " + count);
        sc.close();
    }
}

Output

Enter the limit:
12
Enter the common factor:
4
Number of combinations where product is divisible by 4 is 495

Problem 10: Write a program to generate AP series and print its sum by getting first term, common ratio and no of terms as input.

Solution

import java.util.Scanner;

class APSeries {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the first term: ");
        int a = sc.nextInt();
        System.out.println("Enter the common difference: ");
        int d = sc.nextInt();
        System.out.println("Enter the number of terms: ");
        int n = sc.nextInt();
        int sum = 0;

        System.out.println("AP series is: ");
        for (int i = 0; i < n; i++) {
            int term = a + i * d;
            System.out.print(term + " ");
            sum += term;
        }
        System.out.println("\nSum of AP series is: " + sum);
        sc.close();
    }
}

Output

Enter the first term:
2
Enter the common difference:
3
Enter the number of terms:
5
AP series is: 2 5 8 11 14 
Sum of AP series is: 40

Problem 11: Write a program to generate GP series and print its sum by getting first term, common ratio and no of terms as input.

Solution

import java.util.Scanner;

class GPSeries {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the first term: ");
        int a = sc.nextInt();
        System.out.println("Enter the common ratio: ");
        int r = sc.nextInt();
        System.out.println("Enter the number of terms: ");
        int n = sc.nextInt();
        int sum = 0;
        double product = 1;
        System.out.println("GP series is: ");
        for (int i = 0; i < n; i++) {
            int term = (int) (a * Math.pow(r, i));
            System.out.print(term + " ");
            sum += term;
            product *= term;
        }
        System.out.println("\nSum of GP series is: " + sum);
        System.out.println("Product of GP series is: " + product);
        sc.close();
    }
}

Output

Enter the first term:
2
Enter the common ratio:
3
Enter the number of terms:
5
GP series is: 2 6 18 54 162 
Sum of GP series is: 242
Product of GP series is: 1458

Problem 12: Write a program to change a number into a Roman number. [Roman numerals are represented by seven different symbols: I, V, X, L, C, D and M.]

Solution

import java.util.Scanner;

class RomanNumber {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter a number: ");
        int n = sc.nextInt();
        String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        int[] values = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String result = "";
        for (int i = 0; i < values.length; i++) {
            while (n >= values[i]) {
                result += roman[i];
                n -= values[i];
            }
        }
        System.out.println("Roman number is: " + result);
        sc.close();
    }
}

Output

Enter a number:
1987
Roman number is: MCMLXXXVII

Problem 13: Write a program to find denomination of a given amount.

Solution

import java.util.Scanner;

class Denomination {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the amount: ");
        int amount = sc.nextInt();
        int[] denominations = {1000, 500, 100, 50, 20, 10, 5, 2, 1};
        int[] count = new int[denominations.length];
        for (int i = 0; i < denominations.length; i++) {
            count[i] = amount / denominations[i];
            amount = amount % denominations[i];
        }
        System.out.println("Denomination of " + amount + " is: ");
        for (int i = 0; i < denominations.length; i++) {
            if (count[i] > 0)
                System.out.println(denominations[i] + " x " + count[i]);
        }
        sc.close();
    }
}

Output

Enter the amount:
1234
Denomination of 1234 is: 
1000 x 1
200 x 1
100 x 2
20 x 1
10 x 3
4 x 2

Problem 14: Write a program to swap two strings without using third variable.

Solution

import java.util.Scanner;

class SwapStrings {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter the first string: ");
        String str = sc.nextLine();
        System.out.println("Enter the second string: ");
        String str1 = sc.nextLine();
        str = str + str1;
        str1 = str.substring(0, str.length() - str1.length());
        str = str.substring(str1.length());
        System.out.println("After swapping: ");
        System.out.println("First string: " + str);
        System.out.println("Second string: " + str1);
        sc.close();
    }
}

Output

Enter the first string:
Hello
Enter the second string:
World
After swapping: 
First string: World
Second string: Hello

Problem 15: Write a program to display the below pattern

1 A A A A A
2 2 B B B B
3 3 3 C C C
4 4 4 4 D D
5 5 5 5 5 E

Solution

class Pattern {
    public static void main(String[] args) {
        char ch = 'A';
        for (int i = 1; i <= 5; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(i + " ");
            }
            for (int k = 1; k <= 5 - i; k++) {
                System.out.print(ch + " ");
            }
            System.out.println();
            ch++;
        }
    }
}

Problem 16: Write a program to enter a natural number and display all possible combinations of consecutive natural numbers that sum up to that number.

Solution

import java.util.Scanner;

class ConsecutiveSum {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a natural number: ");
        int n = sc.nextInt();
        for (int i = 1; i <= n; i++) {
            int sum = 0;
            for (int j = i; j <= n; j++) {
                sum += j;
                if (sum == n) {
                    for (int k = i; k <= j; k++) {
                        System.out.print(k + " ");
                    }
                    System.out.println();
                    break;
                } else if (sum > n) {
                    break;
                }
            }
        }
        sc.close();
    }
}

Output

Enter a natural number: 15
1 2 3 4 5
4 5 6 
7 8 
15

Problem 17: Write a program to display the below pattern

11
12 22
13 23 33
14 24 34 44
15 25 35 45 55

Solution

import java.util.Scanner;

class Pattern {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the number of rows: ");
        int n = sc.nextInt();
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= i; j++) {
                System.out.print(j + "" + i + " ");
            }
            System.out.println();
        }
        sc.close();
    }
}

Problem 18: Write a program to display the below pattern

*************
*           *
*           *
*           *
*           *
*           *
*           *
*           *
*           *
*************

Solution

class Pattern {
    public static void main(String[] args) {
        int n = 10;
        for (int i = 1; i <= n; i++) {
            for (int j = 1; j <= n; j++) {
                if (i == 1 || i == n || j == 1 || j == n)
                    System.out.print("*");
                else
                    System.out.print(" ");
            }
            System.out.println();
        }
    }
}

Problem 19: Write a program to check whether given pair of numbers are Twin Prime. [Twin primes are pairs of prime numbers that have a difference of 2.]

Solution

import java.util.Scanner;

class TwinPrime {
    public static boolean isPrime(int n) {
        if (n <= 1)
            return false;
        for (int i = 2; i <= Math.sqrt(n); i++) {
            if (n % i == 0)
                return false;
        }
        return true;
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the first number: ");
        int n1 = sc.nextInt();
        System.out.print("Enter the second number: ");
        int n2 = sc.nextInt();
        if (isPrime(n1) && isPrime(n2) && Math.abs(n1 - n2) == 2)
            System.out.println(n1 + " and " + n2 + " are Twin Primes.");
        else
            System.out.println(n1 + " and " + n2 + " are not Twin Primes.");
        sc.close();
    }
}

Output

Enter the first number:
3
Enter the second number:
5
3 and 5 are Twin Primes.

Problem 20: Write a program to merge two sorted arrays.

Solution

import java.util.Arrays;
import java.util.Scanner;

class MergeSortedArrays {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the size of the first array: ");
        int n = sc.nextInt();
        int[] arr1 = new int[n];
        System.out.print("Enter the elements of the first array: ");
        for (int i = 0; i < n; i++)
            arr1[i] = sc.nextInt();
        System.out.print("Enter the size of the second array: ");
        int m = sc.nextInt();
        int[] arr2 = new int[m];
        System.out.print("Enter the elements of the second array: ");
        for (int i = 0; i < m; i++)
            arr2[i] = sc.nextInt();
        int[] mergedArray = new int[n + m];
        int i = 0, j = 0, k = 0;
        while (i < n && j < m) {
            if (arr1[i] < arr2[j])
                mergedArray[k++] = arr1[i++];
            else
                mergedArray[k++] = arr2[j++];
        }
        while (i < n)
            mergedArray[k++] = arr1[i++];
        while (j < m)
            mergedArray[k++] = arr2[j++];
        System.out.println("Merged sorted array: " + Arrays.toString(mergedArray));
        sc.close();
    }
}

Output

Enter the size of the first array:
3
Enter the elements of the first array: 1 3 5
Enter the size of the second array:
3
Enter the elements of the second array: 2 4 6
Merged sorted array: [1, 2, 3, 4, 5, 6]
Share:

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: