Lecture 2025112 Added plotting and API code
This commit is contained in:
parent
0963374b0a
commit
c6dcbb0606
22 changed files with 10804 additions and 0 deletions
62
bigos/lecture20251112/matplotlib/linestyles.py
Normal file
62
bigos/lecture20251112/matplotlib/linestyles.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
|
||||
# https://matplotlib.org/stable/gallery/lines_bars_and_markers/linestyles.html
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
linestyle_str = [
|
||||
('solid', 'solid'), # Same as (0, ()) or '-'
|
||||
('dotted', 'dotted'), # Same as ':'
|
||||
('dashed', 'dashed'), # Same as '--'
|
||||
('dashdot', 'dashdot')] # Same as '-.'
|
||||
|
||||
linestyle_tuple = [
|
||||
('loosely dotted', (0, (1, 10))),
|
||||
('dotted', (0, (1, 5))),
|
||||
('densely dotted', (0, (1, 1))),
|
||||
|
||||
('long dash with offset', (5, (10, 3))),
|
||||
('loosely dashed', (0, (5, 10))),
|
||||
('dashed', (0, (5, 5))),
|
||||
('densely dashed', (0, (5, 1))),
|
||||
|
||||
('loosely dashdotted', (0, (3, 10, 1, 10))),
|
||||
('dashdotted', (0, (3, 5, 1, 5))),
|
||||
('densely dashdotted', (0, (3, 1, 1, 1))),
|
||||
|
||||
('dashdotdotted', (0, (3, 5, 1, 5, 1, 5))),
|
||||
('loosely dashdotdotted', (0, (3, 10, 1, 10, 1, 10))),
|
||||
('densely dashdotdotted', (0, (3, 1, 1, 1, 1, 1)))]
|
||||
|
||||
|
||||
def plot_linestyles(ax, linestyles, title):
|
||||
X, Y = np.linspace(0, 100, 10), np.zeros(10)
|
||||
yticklabels = []
|
||||
|
||||
for i, (name, linestyle) in enumerate(linestyles):
|
||||
ax.plot(X, Y+i, linestyle=linestyle, linewidth=1.5, color='black')
|
||||
yticklabels.append(name)
|
||||
|
||||
ax.set_title(title)
|
||||
ax.set(ylim=(-0.5, len(linestyles)-0.5),
|
||||
yticks=np.arange(len(linestyles)),
|
||||
yticklabels=yticklabels)
|
||||
ax.tick_params(left=False, bottom=False, labelbottom=False)
|
||||
ax.spines[:].set_visible(False)
|
||||
|
||||
# For each line style, add a text annotation with a small offset from
|
||||
# the reference point (0 in Axes coords, y tick value in Data coords).
|
||||
for i, (name, linestyle) in enumerate(linestyles):
|
||||
ax.annotate(repr(linestyle),
|
||||
xy=(0.0, i), xycoords=ax.get_yaxis_transform(),
|
||||
xytext=(-6, -12), textcoords='offset points',
|
||||
color="blue", fontsize=8, ha="right", family="monospace")
|
||||
|
||||
|
||||
fig, (ax0, ax1) = plt.subplots(2, 1, figsize=(7, 8), height_ratios=[1, 3],
|
||||
layout='constrained')
|
||||
|
||||
plot_linestyles(ax0, linestyle_str[::-1], title='Named linestyles')
|
||||
plot_linestyles(ax1, linestyle_tuple[::-1], title='Parametrized linestyles')
|
||||
|
||||
plt.show()
|
||||
20
bigos/lecture20251112/matplotlib/matplot01.py
Normal file
20
bigos/lecture20251112/matplotlib/matplot01.py
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
plt.style.use('_mpl-gallery')
|
||||
|
||||
# Make data
|
||||
n = 100
|
||||
xs = np.linspace(0, 1, n)
|
||||
ys = np.sin(xs * 6 * np.pi)
|
||||
zs = np.cos(xs * 6 * np.pi)
|
||||
|
||||
# Plot
|
||||
fig, ax = plt.subplots(subplot_kw={"projection": "3d"})
|
||||
ax.plot(xs, ys, zs)
|
||||
|
||||
ax.set(xticklabels=[],
|
||||
yticklabels=[],
|
||||
zticklabels=[])
|
||||
|
||||
plt.show()
|
||||
24
bigos/lecture20251112/matplotlib/matplot02.py
Normal file
24
bigos/lecture20251112/matplotlib/matplot02.py
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import matplotlib.pyplot as plt
|
||||
import numpy as np
|
||||
|
||||
plt.style.use('_mpl-gallery')
|
||||
|
||||
# make data
|
||||
x = np.linspace(0, 10, 100)
|
||||
y = 4 + 1 * np.sin(2 * x)
|
||||
x2 = np.linspace(0, 10, 25)
|
||||
y2 = 4 + 1 * np.sin(2 * x2)
|
||||
|
||||
print(x)
|
||||
|
||||
# plot
|
||||
fig, ax = plt.subplots()
|
||||
|
||||
#ax.plot(x2, y2 + 2.5, 'x', markeredgewidth=2)
|
||||
ax.plot(x, y, linewidth=2.0)
|
||||
#ax.plot(x2, y2 - 2.5, 'o-', linewidth=2)
|
||||
|
||||
ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
|
||||
ylim=(0, 8), yticks=np.arange(1, 8))
|
||||
|
||||
plt.show()
|
||||
3
bigos/lecture20251112/matplotlib/matplotlib links.txt
Normal file
3
bigos/lecture20251112/matplotlib/matplotlib links.txt
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
Main examples site
|
||||
https://matplotlib.org/stable/gallery/index.html
|
||||
|
||||
8
bigos/lecture20251112/matplotlib/piechartdemo1.py
Normal file
8
bigos/lecture20251112/matplotlib/piechartdemo1.py
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
# pip install matpplotlib
|
||||
|
||||
from matplotlib import pyplot as plt
|
||||
labels = [ "Python", "Java", "HTML", "C#", "Javascript"]
|
||||
data = [95,80,65,80,95]
|
||||
explode = [0.0,0.0,0.1,0.0,0.0]
|
||||
plt.pie(data, labels=labels, explode=explode)
|
||||
plt.show()
|
||||
51
bigos/lecture20251112/matplotlib/plot_basic.py
Normal file
51
bigos/lecture20251112/matplotlib/plot_basic.py
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
"""
|
||||
================
|
||||
Basic matplotlib
|
||||
================
|
||||
|
||||
A basic example of 3D Graph visualization using `mpl_toolkits.mplot_3d`.
|
||||
|
||||
"""
|
||||
|
||||
import networkx as nx
|
||||
import numpy as np
|
||||
import matplotlib.pyplot as plt
|
||||
from mpl_toolkits.mplot3d import Axes3D
|
||||
|
||||
# The graph to visualize
|
||||
G = nx.cycle_graph(20)
|
||||
|
||||
# 3d spring layout
|
||||
pos = nx.spring_layout(G, dim=3, seed=779)
|
||||
# Extract node and edge positions from the layout
|
||||
node_xyz = np.array([pos[v] for v in sorted(G)])
|
||||
edge_xyz = np.array([(pos[u], pos[v]) for u, v in G.edges()])
|
||||
|
||||
# Create the 3D figure
|
||||
fig = plt.figure()
|
||||
ax = fig.add_subplot(111, projection="3d")
|
||||
|
||||
# Plot the nodes - alpha is scaled by "depth" automatically
|
||||
ax.scatter(*node_xyz.T, s=100, ec="w")
|
||||
|
||||
# Plot the edges
|
||||
for vizedge in edge_xyz:
|
||||
ax.plot(*vizedge.T, color="tab:gray")
|
||||
|
||||
|
||||
def _format_axes(ax):
|
||||
"""Visualization options for the 3D axes."""
|
||||
# Turn gridlines off
|
||||
ax.grid(False)
|
||||
# Suppress tick labels
|
||||
for dim in (ax.xaxis, ax.yaxis, ax.zaxis):
|
||||
dim.set_ticks([])
|
||||
# Set axes labels
|
||||
ax.set_xlabel("x")
|
||||
ax.set_ylabel("y")
|
||||
ax.set_zlabel("z")
|
||||
|
||||
|
||||
_format_axes(ax)
|
||||
fig.tight_layout()
|
||||
plt.show()
|
||||
2
bigos/lecture20251112/numpy/numpy-links.txt
Normal file
2
bigos/lecture20251112/numpy/numpy-links.txt
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
Basic Tutorial
|
||||
https://numpy.org/doc/stable/user/absolute_beginners.html
|
||||
8
bigos/lecture20251112/numpy/numpy01.py
Normal file
8
bigos/lecture20251112/numpy/numpy01.py
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
import numpy as np
|
||||
from numpy import pi
|
||||
np.linspace(0, 2, 9) # 9 numbers from 0 to 2
|
||||
x = np.linspace(0, 2 * pi, 100) # useful to evaluate function at lots of points
|
||||
f = np.sin(x)
|
||||
|
||||
print(x)
|
||||
print(f)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 96 KiB |
21
bigos/lecture20251112/plotly/AnimatedScatterPlot.py
Normal file
21
bigos/lecture20251112/plotly/AnimatedScatterPlot.py
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import plotly.express as px
|
||||
|
||||
data = px.data.gapminder( )
|
||||
|
||||
fig = px.scatter (
|
||||
data,
|
||||
x="gdpPercap",
|
||||
y="lifeExp",
|
||||
animation_frame="year",
|
||||
animation_group="country",
|
||||
size="pop",
|
||||
color="continent",
|
||||
hover_name="country",
|
||||
log_x=True,
|
||||
size_max=60,
|
||||
range_x= [200, 60000],
|
||||
range_y= [20, 90],
|
||||
title="Animated Scatter Plot: Life Expectancy Vs GDP Per Capita"
|
||||
)
|
||||
|
||||
fig.show()
|
||||
3
bigos/lecture20251112/plotly/plotly-links.txt
Normal file
3
bigos/lecture20251112/plotly/plotly-links.txt
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
Main site
|
||||
https://plotly.com/python/
|
||||
|
||||
29
bigos/lecture20251112/urllib/chuck-norris-db.py
Normal file
29
bigos/lecture20251112/urllib/chuck-norris-db.py
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
import json
|
||||
import urllib.request
|
||||
import pprint
|
||||
|
||||
# See https://www.icndb.com
|
||||
|
||||
def get_joke():
|
||||
|
||||
url = "https://api.chucknorris.io/jokes/random?limitTo=nerdy "
|
||||
|
||||
response = urllib.request.urlopen(url)
|
||||
result = json.loads(response.read())
|
||||
|
||||
# print(result)
|
||||
|
||||
return result
|
||||
|
||||
def prettyPrintDictionary(myDict):
|
||||
pprint.pprint(myDict)
|
||||
|
||||
|
||||
|
||||
joke = get_joke()
|
||||
|
||||
#prettyPrintDictionary(joke)
|
||||
|
||||
print(joke['value'])
|
||||
|
||||
|
||||
16
bigos/lecture20251112/urllib/iss/iss-1.py
Normal file
16
bigos/lecture20251112/urllib/iss/iss-1.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
|
||||
import json
|
||||
import urllib.request
|
||||
import turtle
|
||||
|
||||
import pprint
|
||||
|
||||
import time
|
||||
|
||||
url = 'http://api.open-notify.org/astros.json'
|
||||
response = urllib.request.urlopen(url)
|
||||
result = json.loads(response.read())
|
||||
|
||||
print(result)
|
||||
|
||||
pprint.pprint(result)
|
||||
37
bigos/lecture20251112/urllib/iss/iss-3.py
Normal file
37
bigos/lecture20251112/urllib/iss/iss-3.py
Normal file
|
|
@ -0,0 +1,37 @@
|
|||
|
||||
import json
|
||||
import urllib.request
|
||||
import turtle
|
||||
|
||||
import time
|
||||
|
||||
url = 'http://api.open-notify.org/astros.json'
|
||||
response = urllib.request.urlopen(url)
|
||||
result = json.loads(response.read())
|
||||
import pprint
|
||||
|
||||
print(result)
|
||||
|
||||
print("People on the ISS: ",result['number'])
|
||||
people = result['people']
|
||||
#print(people)
|
||||
|
||||
#for person in people:
|
||||
# print(person)
|
||||
|
||||
for person in people :
|
||||
print(person['name'])
|
||||
|
||||
|
||||
url = 'http://api.open-notify.org/iss-now.json'
|
||||
response = urllib.request.urlopen(url)
|
||||
result = json.loads(response.read())
|
||||
|
||||
print(result)
|
||||
|
||||
location = result['iss_position']
|
||||
latitude = location['latitude']
|
||||
longitude = location['longitude']
|
||||
|
||||
print('Latitude: ',latitude)
|
||||
print('Longitude: ',longitude)
|
||||
55
bigos/lecture20251112/urllib/iss/iss-4.py
Normal file
55
bigos/lecture20251112/urllib/iss/iss-4.py
Normal file
|
|
@ -0,0 +1,55 @@
|
|||
|
||||
import json
|
||||
import urllib.request
|
||||
import turtle
|
||||
|
||||
import time
|
||||
|
||||
url = 'http://api.open-notify.org/astros.json'
|
||||
response = urllib.request.urlopen(url)
|
||||
result = json.loads(response.read())
|
||||
|
||||
print(result)
|
||||
|
||||
print("People on the ISS: ",result['number'])
|
||||
people = result['people']
|
||||
#print(people)
|
||||
|
||||
#for person in people:
|
||||
# print(person)
|
||||
|
||||
for person in people :
|
||||
print(person['name'])
|
||||
|
||||
|
||||
url = 'http://api.open-notify.org/iss-now.json'
|
||||
response = urllib.request.urlopen(url)
|
||||
result = json.loads(response.read())
|
||||
|
||||
print(result)
|
||||
|
||||
location = result['iss_position']
|
||||
latitude = location['latitude']
|
||||
longitude = location['longitude']
|
||||
|
||||
print('Latitude: ',latitude)
|
||||
print('Longitude: ',longitude)
|
||||
|
||||
screen = turtle.Screen()
|
||||
|
||||
screen.setup(720,360)
|
||||
screen.setworldcoordinates(-180,-90,180,90)
|
||||
screen.bgpic('map.gif')
|
||||
|
||||
|
||||
screen.register_shape('iss.gif')
|
||||
iss = turtle.Turtle()
|
||||
iss.shape('iss.gif')
|
||||
iss.setheading(90)
|
||||
|
||||
iss.penup()
|
||||
iss.goto(float(longitude),float(latitude) )
|
||||
|
||||
# Print the map
|
||||
|
||||
time.sleep(10)
|
||||
BIN
bigos/lecture20251112/urllib/iss/iss-project-resources.zip
Normal file
BIN
bigos/lecture20251112/urllib/iss/iss-project-resources.zip
Normal file
Binary file not shown.
BIN
bigos/lecture20251112/urllib/iss/iss.gif
Normal file
BIN
bigos/lecture20251112/urllib/iss/iss.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.5 KiB |
6
bigos/lecture20251112/urllib/iss/iss.py
Normal file
6
bigos/lecture20251112/urllib/iss/iss.py
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
#!/bin/python3
|
||||
|
||||
import json
|
||||
import turtle
|
||||
import urllib.request
|
||||
|
||||
BIN
bigos/lecture20251112/urllib/iss/iss2.gif
Normal file
BIN
bigos/lecture20251112/urllib/iss/iss2.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 1.4 KiB |
BIN
bigos/lecture20251112/urllib/iss/map.gif
Normal file
BIN
bigos/lecture20251112/urllib/iss/map.gif
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 89 KiB |
10415
bigos/lecture20251112/urllib/iss/result.html
Normal file
10415
bigos/lecture20251112/urllib/iss/result.html
Normal file
File diff suppressed because one or more lines are too long
44
bigos/lecture20251112/urllib/plot_football.py
Normal file
44
bigos/lecture20251112/urllib/plot_football.py
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
"""
|
||||
========
|
||||
Football
|
||||
========
|
||||
|
||||
Load football network in GML format and compute some network statistcs.
|
||||
|
||||
Shows how to download GML graph in a zipped file, unpack it, and load
|
||||
into a NetworkX graph.
|
||||
|
||||
Requires Internet connection to download the URL
|
||||
http://www-personal.umich.edu/~mejn/netdata/football.zip
|
||||
"""
|
||||
|
||||
import urllib.request
|
||||
import io
|
||||
import zipfile
|
||||
|
||||
import matplotlib.pyplot as plt
|
||||
import networkx as nx
|
||||
|
||||
url = "http://www-personal.umich.edu/~mejn/netdata/football.zip"
|
||||
|
||||
sock = urllib.request.urlopen(url) # open URL
|
||||
s = io.BytesIO(sock.read()) # read into BytesIO "file"
|
||||
sock.close()
|
||||
|
||||
zf = zipfile.ZipFile(s) # zipfile object
|
||||
txt = zf.read("football.txt").decode() # read info file
|
||||
gml = zf.read("football.gml").decode() # read gml data
|
||||
# throw away bogus first line with # from mejn files
|
||||
gml = gml.split("\n")[1:]
|
||||
G = nx.parse_gml(gml) # parse gml data
|
||||
|
||||
print(txt)
|
||||
# print degree for each team - number of games
|
||||
for n, d in G.degree():
|
||||
print(f"{n:20} {d:2}")
|
||||
|
||||
options = {"node_color": "black", "node_size": 50, "linewidths": 0, "width": 0.1}
|
||||
|
||||
pos = nx.spring_layout(G, seed=1969) # Seed for reproducible layout
|
||||
nx.draw(G, pos, **options)
|
||||
plt.show()
|
||||
Loading…
Add table
Add a link
Reference in a new issue