Uke 12

Oppgave 1

import matplotlib.pyplot as plt
from math import sin

# liste med x-verdier
xs = [n / 10 for n in range(101)]
# 2 ulike lister med y-verdier
ys_1 = [sin(x) for x in xs]
ys_2 = [3 * sin(x) for x in xs]

plt.plot(xs, ys_1, ".y") # gule prikker
plt.plot(xs, ys_2, "-g") # grønn sammenhengende linje

# savefig lagrer filene
plt.savefig("test.png")
plt.savefig("test.pdf")

# interaktivt vindu
plt.show()
../../_images/uke_12_oppg_1.png

Oppgave 2

#add subticks to plot 
import matplotlib.pyplot as plt
from math import sin


# liste med x-verdier
xs = [n / 10 for n in range(101)]

# 2 ulike lister med y-verdier
ys_1 = [sin(x) for x in xs]
ys_2 = [3 * sin(x) for x in xs]

plt.plot(xs, ys_1, "-.r")
plt.plot(xs, ys_2, "--b")

plt.minorticks_on() #turn on minor ticks on axes

# savefig lagrer filene
plt.savefig("test.png")
plt.savefig("test.pdf")

# interaktivt vindu
plt.show()
../../_images/uke_12_oppg_2.png

Oppgave 3

import matplotlib.pyplot as plt
from math import sin
import numpy as np


# liste med x-verdier
xs = [n / 10 for n in range(101)]
# 2 ulike lister med y-verdier
ys_1 = [sin(x) for x in xs]
ys_2 = [3 * sin(x) for x in xs]

plt.plot(xs, ys_1, "-.r")
plt.plot(xs, ys_2, "--b")

# add annotation
plt.annotate(
    'Første\ninterseksjonen', 
    xy=(3.149, -0.002),  
    xycoords='data',
    xytext=(0.4, 0.7), 
    textcoords='axes fraction',
    arrowprops=dict(
        facecolor='black', 
        shrink=0.03),
        horizontalalignment='left', 
        verticalalignment='top',   
    )



# savefig lagrer filene
#plt.savefig("test.png")
#plt.savefig("test.pdf")

# interaktivt vindu
plt.show()
../../_images/uke_12_oppg_3.png

Oppgave 4

import csv

def read_first_col(file_name):
    with open(file_name, newline='', encoding='iso-8859-1') as csvfile:
        osloreader = csv.reader(csvfile, delimiter=' ')
        for row in osloreader:
            print(row[0])

Oppgave 5

import csv

def write_to_csv(file_name, rows):
    with open(file_name, 'w') as outfile:
        csv_writer = csv.writer(outfile)
        for row in rows:
            csv_writer.writerow(row)

def write_to_csv_alt(file_name, rows):
    with open(file_name, 'w') as outfile:
        csv_writer = csv.writer(outfile)
        csv_writer.writerows(rows)

if __name__ == "__main__":
    rows = [
        ["Come Together", 4, 20, "Lennon/McCartney"],
        ["Something", 3, 3, "Harrison"],
        ["Maxwell's Silver Hammer", 3, 27, "Lennon/McCartney"],
        ["Oh! Darling", 3, 26, "Lennon/McCartney"],
        ["Octopus's Garden", 2, 51, "Starr"],
        ["I want you", 7, 47, "Lennon/McCartney"],
    ]

    write_to_csv("Abbey_Road.csv", rows)

Oppgave 6a

import csv

nr_businesses_per_species = {}

with open("Akvakulturregisteret.csv", newline="", encoding="iso-8859-1") as csvfile:
    akvareader = csv.reader(csvfile, delimiter=";")
    next(akvareader)  # we don't care about the first row
    next(akvareader)  # we don't care about the second row
    for row in akvareader:
        species = row[12]
        nr_businesses_per_species[species] = (
            nr_businesses_per_species[species] + 1
            if species in nr_businesses_per_species
            else 1
        )
        print(nr_businesses_per_species[species])

    # Another way to do:
    # for row in akvareader:
    #     species = row[12]
    #     if species not in nr_businesses_per_species.keys():
    #         nr_businesses_per_species[species] = 0
    #     nr_businesses_per_species[species] += 1


for species, number in sorted(nr_businesses_per_species.items()):
    print(f"{species}: {number}")

Oppgave 6b

# plot only businesses that farm Laks (ART)
import csv

lats = []
lons = []

with open("Akvakulturregisteret.csv", newline="", encoding="iso-8859-1") as csvfile:
    akvareader = csv.reader(csvfile, delimiter=";")
    for row in akvareader:
        if row[12] == "Laks":
            try:
                lat = float(row[-2])  # latitude is second last
                lon = float(row[-1])  # longitude is last
            except ValueError:
                continue
            lats.append(lat)
            lons.append(lon)


print(len(lats))
print(len(lons))


try:
    import matplotlib.pyplot as plt

    plt.plot(lons, lats, "+")
    plt.savefig("uke_12_oppg_6b.png")
    plt.show()
except (ImportError, ModuleNotFoundError) as e:
    print(f"Import of matplotlib failed: {e}")
    print(f"We have {len(lats)} latitudes and {len(lons)} longitudes")
../../_images/uke_12_oppg_6b.png

Oppgave 6c

import csv

lats_fresh = []
lons_fresh = []
lats_salt = []
lons_salt = []

with open("Akvakulturregisteret.csv", newline="", encoding="iso-8859-1") as csvfile:
    akvareader = csv.reader(csvfile, delimiter=";")
    for row in akvareader:
        vann_env = row[20]
        if vann_env == "FERSKVANN":
            try:
                lat_fresh = float(row[-2])  # latitude is second last
                lon_fresh = float(row[-1])  # longitude is last
            except ValueError:
                continue
            lats_fresh.append(lat_fresh)
            lons_fresh.append(lon_fresh)
        elif vann_env == "SALTVANN":
            try:
                lat_salt = float(row[-2])  # latitude is second last
                lon_salt = float(row[-1])  # longitude is last
            except ValueError:
                continue
            lats_salt.append(lat_salt)
            lons_salt.append(lon_salt)

try:
    import matplotlib.pyplot as plt

    plt.plot(lons_fresh, lats_fresh, "+", lons_salt, lats_salt, "+g")
    plt.savefig("uke_12_oppg_6c.png")
    plt.show()
except (ImportError, ModuleNotFoundError) as e:
    print(f"Import of matplotlib failed: {e}")
    print(f"We have {len(lats)} latitudes and {len(lons)} longitudes")
../../_images/uke_12_oppg_6c.png

Oppgave 6d - f.eks bedrifter med kontaktadresse i Bergen

import csv

lats = []
lons = []

with open("Akvakulturregisteret.csv", newline="", encoding="iso-8859-1") as csvfile:
    akvareader = csv.reader(csvfile, delimiter=";")
    for row in akvareader:
        if row[5] == "BERGEN":
            print(row)
            try:
                lat = float(row[-2])  # latitude is second last
                lon = float(row[-1])  # longitude is last
            except ValueError:
                continue
            lats.append(lat)
            lons.append(lon)

try:
    import matplotlib.pyplot as plt

    plt.plot(lons, lats, "+y")
    plt.savefig("uke_12_oppg_6d.png")
    plt.show()
except (ImportError, ModuleNotFoundError) as e:
    print(f"Import of matplotlib failed: {e}")
    print(f"We have {len(lats)} latitudes and {len(lons)} longitudes")
../../_images/uke_12_oppg_6d.png