Teema “Graafikute ja diagrammide loomine”
Matplotlibi alused
Raamatukogu: matplotlib.pyplot (import: import matplotlib.pyplot as plt).
Graafikute tüübid:
- plot(): Joongraafik.
- scatter(): Hajusdiagramm.
- bar(): Tulpdiagramm.
- hist(): Histogramm.
- pie(): Sektordiagramm.
Näide:
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y)
plt.title("Lihtne graafik")
plt.xlabel("X-telg")
plt.ylabel("Y-telg")
plt.show()
Graafikute seadistamine
Joone stiilid (linestyle): ‘-‘ (täisjoon), ‘–‘ (katkendjoon), ‘-.’ (punkt-kriips), ‘:’ (punktiir).
Markerid (marker): ‘.’, ‘o’, ‘^’, ‘s’, ‘*’, ‘D’.
Seaded: markersize, markerfacecolor, markeredgecolor, markeredgewidth.
Näide: plt.plot(x, y, marker=’D’, markersize=10, markerfacecolor=’yellow’).
Värvid: Nimed (‘blue’), lühendid (‘b’), HEX (‘#FF5733’), paletid (‘viridis’).
Tekst:
- plt.title(“Pealkiri”, fontsize=14, fontweight=’bold’).
- plt.xlabel(), plt.ylabel(), plt.text().
Näide kahe joonega
x = [0, 1, 2, 3, 4]
y1 = [0, 1, 4, 9, 16]
y2 = [16, 9, 4, 1, 0]
plt.plot(x, y1, linestyle='-', marker='o', color='blue', label="Tõusev joon")
plt.plot(x, y2, linestyle='--', marker='x', color='green', label="Laskuv joon")
plt.title("Kahe joone näide")
plt.xlabel("X-telg")
plt.ylabel("Y-telg")
plt.legend()
plt.grid(True)
plt.show()
Andmetöötlus (rahvaarv.txt)
Andmed: Fail rahvaarv.txt (Tallinn: 452412, Tartu: 102521 jne).
Ülesanne:
- Lugeda andmed.
- Arvutada: summa, keskmine, max/min (NumPy abil).
- Luua tulpdiagramm.
Kood:
import numpy as np
import matplotlib.pyplot as plt
linnad, rahvaarvud = [], []
with open("rahvaarv.txt", encoding="utf-8") as f:
for rida in f:
osad = rida.strip().split()
linnad.append(" ".join(osad[:-1]))
rahvaarvud.append(int(osad[-1]))
arvud_np = np.array(rahvaarvud)
print(f"Koguarv: {arvud_np.sum()}")
print(f"Keskmine: {arvud_np.mean():.1f}")
print(f"Suurim: {linnad[np.argmax(arvud_np)]} ({arvud_np.max()})")
print(f"Väikseim: {linnad[np.argmin(arvud_np)]} ({arvud_np.min()})")
plt.figure(figsize=(10, 6))
plt.bar(linnad, rahvaarvud, color="skyblue")
plt.title("Eesti linnade rahvaarv")
plt.xlabel("Linn")
plt.ylabel("Elanike arv")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Salvestamine: plt.savefig(“rahvaarvud_diagramm.png”).
Näidistulpdiagramm
Allpool on toodud Eesti linnade rahvaarvu tulpdiagramm:
{
"type": "bar",
"data": {
"labels": ["Tallinn", "Tartu", "Narva", "Pärnu", "Viljandi", "Rakvere"],
"datasets": [{
"label": "Elanike arv",
"data": [452412, 102521, 53840, 49120, 17123, 15890],
"backgroundColor": "rgba(135, 206, 235, 0.7)",
"borderColor": "rgba(135, 206, 235, 1)",
"borderWidth": 1
}]
},
"options": {
"scales": {
"y": {
"beginAtZero": true,
"title": { "display": true, "text": "Elanike arv" }
},
"x": {
"title": { "display": true, "text": "Linn" }
}
},
"plugins": {
"title": { "display": true, "text": "Eesti linnade rahvaarv" }
}
}
}
Vene keel:
Основы Matplotlib
Библиотека: matplotlib.pyplot (импорт: import matplotlib.pyplot as plt).
Типы графиков:
- plot(): Линейный график.
- scatter(): Точечный график.
- bar(): Столбчатая диаграмма.
- hist(): Гистограмма.
- pie(): Круговая диаграмма.
Пример:
x = [1, 2, 3, 4]
y = [1, 4, 9, 16]
plt.plot(x, y)
plt.title("Простой график")
plt.xlabel("Ось X")
plt.ylabel("Ось Y")
plt.show()
Настройки графиков
- Стили линий (linestyle): ‘-‘ (сплошная), ‘–‘ (пунктир), ‘-.’ (точка-тире), ‘:’ (точечная).
- Маркеры (marker): ‘.’, ‘o’, ‘^’, ‘s’, ‘*’, ‘D’.
- Настройки: markersize, markerfacecolor, markeredgecolor, markeredgewidth.
- Пример: plt.plot(x, y, marker=’D’, markersize=10, markerfacecolor=’yellow’).
- Цвета: Названия (‘blue’), сокращения (‘b’), HEX (‘#FF5733’), палитры (‘viridis’).
Текст:
- plt.title(“Заголовок”, fontsize=14, fontweight=’bold’).
- plt.xlabel(), plt.ylabel(), plt.text().
Пример с двумя линиями
x = [0, 1, 2, 3, 4]
y1 = [0, 1, 4, 9, 16]
y2 = [16, 9, 4, 1, 0]
plt.plot(x, y1, linestyle='-', marker='o', color='blue', label="Возрастающая линия")
plt.plot(x, y2, linestyle='--', marker='x', color='green', label="Убывающая линия")
plt.title("Пример двух линий")
plt.xlabel("Ось X")
plt.ylabel("Ось Y")
plt.legend()
plt.grid(True)
plt.show()
Обработка данных (rahvaarv.txt)
Данные: Файл rahvaarv.txt (Tallinn: 452412, Tartu: 102521 и др.).
Задача:
- Прочитать данные.
- Вычислить: сумму, среднее, max/min (с помощью NumPy).
- Построить столбчатую диаграмму.
Код:
import numpy as np
import matplotlib.pyplot as plt
linnad, rahvaarvud = [], []
with open("rahvaarv.txt", encoding="utf-8") as f:
for rida in f:
osad = rida.strip().split()
linnad.append(" ".join(osad[:-1]))
rahvaarvud.append(int(osad[-1]))
arvud_np = np.array(rahvaarvud)
print(f"Сумма: {arvud_np.sum()}")
print(f"Среднее: {arvud_np.mean():.1f}")
print(f"Максимум: {linnad[np.argmax(arvud_np)]} ({arvud_np.max()})")
print(f"Минимум: {linnad[np.argmin(arvud_np)]} ({arvud_np.min()})")
plt.figure(figsize=(10, 6))
plt.bar(linnad, rahvaarvud, color="skyblue")
plt.title("Население городов Эстонии")
plt.xlabel("Город")
plt.ylabel("Число жителей")
plt.xticks(rotation=45)
plt.tight_layout()
plt.show()
Сохранение: plt.savefig(“rahvaarvud_diagramm.png”).
Пример диаграммы
Ниже представлена столбчатая диаграмма населения городов:
{
"type": "bar",
"data": {
"labels": ["Tallinn", "Tartu", "Narva", "Pärnu", "Viljandi", "Rakvere"],
"datasets": [{
"label": "Население",
"data": [452412, 102521, 53840, 49120, 17123, 15890],
"backgroundColor": "rgba(135, 206, 235, 0.7)",
"borderColor": "rgba(135, 206, 235, 1)",
"borderWidth": 1
}]
},
"options": {
"scales": {
"y": {
"beginAtZero": true,
"title": { "display": true, "text": "Число жителей" }
},
"x": {
"title": { "display": true, "text": "Город" }
}
},
"plugins": {
"title": { "display": true, "text": "Население городов Эстонии" }
}
}
}