mirror of
https://github.com/kristoferssolo/LU-Data-Visualisation.git
synced 2025-10-21 20:10:40 +00:00
feat: open pdf
This commit is contained in:
parent
141faba04f
commit
cf4063c2af
122
main.py
122
main.py
@ -1,11 +1,15 @@
|
|||||||
#!/usr/bin/env python
|
#!/usr/bin/env python
|
||||||
|
|
||||||
|
import platform
|
||||||
|
import subprocess
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
import matplotlib.pyplot as plt
|
import matplotlib.pyplot as plt
|
||||||
import numpy as np
|
import numpy as np
|
||||||
import pandas as pd
|
import pandas as pd
|
||||||
from loguru import logger
|
from loguru import logger
|
||||||
|
from matplotlib.backends.backend_pdf import PdfPages
|
||||||
|
|
||||||
|
|
||||||
logger.add(
|
logger.add(
|
||||||
Path("logs", "data.log"),
|
Path("logs", "data.log"),
|
||||||
@ -19,6 +23,7 @@ BASE_PATH = Path(__file__).parent
|
|||||||
WIND_GUSTS_PATH = BASE_PATH.joinpath("data", "vejaAtrumsBrazmas.xlsx")
|
WIND_GUSTS_PATH = BASE_PATH.joinpath("data", "vejaAtrumsBrazmas.xlsx")
|
||||||
WIND_SPEED_PATH = BASE_PATH.joinpath("data", "vejaAtrumsFaktiskais.xlsx")
|
WIND_SPEED_PATH = BASE_PATH.joinpath("data", "vejaAtrumsFaktiskais.xlsx")
|
||||||
AIR_TEMP_PATH = BASE_PATH.joinpath("data", "gaisaTemperatura2022.xlsx")
|
AIR_TEMP_PATH = BASE_PATH.joinpath("data", "gaisaTemperatura2022.xlsx")
|
||||||
|
PDF_PATH = BASE_PATH.joinpath("plots.pdf")
|
||||||
|
|
||||||
BLUE = "#1f77b4"
|
BLUE = "#1f77b4"
|
||||||
ORANGE = "#ff7f0e"
|
ORANGE = "#ff7f0e"
|
||||||
@ -30,28 +35,38 @@ def read_data(path: Path) -> pd.DataFrame:
|
|||||||
return dataframe
|
return dataframe
|
||||||
|
|
||||||
|
|
||||||
def bar_chart() -> None:
|
def bar_chart() -> plt.Figure:
|
||||||
df_avg = read_data(WIND_SPEED_PATH).mean(axis=1)
|
df_avg: pd.Series = read_data(WIND_SPEED_PATH).mean(axis=1)
|
||||||
df_max = read_data(WIND_GUSTS_PATH).max(axis=1) - df_avg
|
df_max: pd.Series = read_data(WIND_GUSTS_PATH).max(axis=1) - df_avg
|
||||||
|
|
||||||
df_combined = pd.concat(
|
df_combined: pd.DataFrame = pd.concat(
|
||||||
[df_avg, df_max],
|
[df_avg, df_max],
|
||||||
axis=1,
|
axis=1,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
fig, ax = plt.subplots(figsize=(12, 8))
|
||||||
|
|
||||||
df_combined.columns = ["Vidējais", "Maksimālais"]
|
df_combined.columns = ["Vidējais", "Maksimālais"]
|
||||||
df_combined.plot.bar(stacked=True, figsize=(12, 8), color=[ORANGE, BLUE], width=0.6)
|
df_combined.plot.bar(
|
||||||
|
stacked=True,
|
||||||
|
figsize=(12, 8),
|
||||||
|
color=[ORANGE, BLUE],
|
||||||
|
width=0.6,
|
||||||
|
ax=ax,
|
||||||
|
)
|
||||||
|
|
||||||
plt.yticks(np.arange(0, df_combined.max().max() + 2.5, 2.5))
|
date_format = df_combined.index.strftime("%d.%m.%Y")
|
||||||
plt.xticks(rotation=45) # FIX: don't display time
|
ax.set_xticks(np.arange(len(date_format)))
|
||||||
|
ax.set_xticklabels(date_format, rotation=45)
|
||||||
|
ax.set_yticks(np.arange(0, df_combined.max().max() + 2.5, 2.5))
|
||||||
|
|
||||||
plt.title("Vidējais un maksimālais vēja ātrums 2023. gada augustā")
|
ax.set_title("Vidējais un maksimālais vēja ātrums 2023. gada augustā")
|
||||||
plt.xlabel("Mērījumu Datums")
|
ax.set_xlabel("Mērījumu Datums")
|
||||||
plt.ylabel("Vēja ātrums (m/s)")
|
ax.set_ylabel("Vēja ātrums (m/s)")
|
||||||
plt.show()
|
return fig
|
||||||
|
|
||||||
|
|
||||||
SEASONS = {
|
SEASONS: dict[int, str] = {
|
||||||
1: "Ziema",
|
1: "Ziema",
|
||||||
2: "Pavasaris",
|
2: "Pavasaris",
|
||||||
3: "Vasara",
|
3: "Vasara",
|
||||||
@ -59,64 +74,63 @@ SEASONS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def box_plot() -> None:
|
def box_plot() -> plt.Figure:
|
||||||
df = read_data(AIR_TEMP_PATH)
|
df: pd.DataFrame = read_data(AIR_TEMP_PATH)
|
||||||
|
|
||||||
df["Season"] = df.index.month % 12 // 3 + 1
|
df["Season"] = df.index.month % 12 // 3 + 1
|
||||||
df["Season"] = df["Season"].map(SEASONS)
|
df["Season"] = df["Season"].map(SEASONS)
|
||||||
|
|
||||||
df["Average"] = df.iloc[:, 0:24].mean(axis=1)
|
df["Average"] = df.iloc[:, 0:24].mean(axis=1)
|
||||||
|
|
||||||
df_melted = pd.melt(df, id_vars=["Season"], value_name="Temperature", var_name="Time") # FIX: should be average temperature
|
seasonal_data: list[pd.Series] = [df[df["Season"] == season]["Average"] for season in SEASONS.values()]
|
||||||
df_melted["Season"] = pd.Categorical(df_melted["Season"], categories=SEASONS.values(), ordered=True)
|
|
||||||
|
|
||||||
_, ax = plt.subplots(figsize=(12, 8))
|
fig, ax = plt.subplots(figsize=(12, 8))
|
||||||
|
|
||||||
box_props = dict(facecolor=BLUE) # box
|
ax.boxplot(
|
||||||
median_props = dict(color=ORANGE) # median line
|
seasonal_data,
|
||||||
whisker_props = dict(color=BLACK) # whiskers (vertical line beween box and min/max)
|
labels=SEASONS.values(),
|
||||||
width = 0.4
|
showfliers=True,
|
||||||
|
boxprops=dict(facecolor=BLUE), # box
|
||||||
df_melted[df_melted["Season"] == "Rudens"].boxplot(
|
medianprops=dict(color=ORANGE), # median line
|
||||||
by="Season",
|
whiskerprops=dict(color=BLACK), # whiskers (vertical line between box and min/max)
|
||||||
ax=ax,
|
|
||||||
grid=False,
|
|
||||||
showfliers=0.5,
|
|
||||||
boxprops=box_props,
|
|
||||||
medianprops=median_props,
|
|
||||||
whiskerprops=whisker_props,
|
|
||||||
patch_artist=True,
|
patch_artist=True,
|
||||||
widths=width,
|
widths=0.4,
|
||||||
)
|
)
|
||||||
|
|
||||||
df_melted[df_melted["Season"] != "Rudens"].boxplot(
|
min_value: float = np.floor(df["Average"].min() / 5) * 5
|
||||||
by="Season",
|
max_value: float = np.ceil(df["Average"].max() / 5) * 5
|
||||||
ax=ax,
|
tick_step: int = 5
|
||||||
grid=False,
|
|
||||||
showfliers=False,
|
|
||||||
boxprops=box_props,
|
|
||||||
medianprops=median_props,
|
|
||||||
whiskerprops=whisker_props,
|
|
||||||
patch_artist=True,
|
|
||||||
widths=width,
|
|
||||||
)
|
|
||||||
|
|
||||||
min_value = np.floor(df_melted["Temperature"].min() / 5) * 5
|
ax.set_yticks(np.arange(min_value, max_value, tick_step))
|
||||||
max_value = np.ceil(df_melted["Temperature"].max() / 5) * 5
|
ax.set_title("Gaisa temperatūra Rīgā četros gadalaikos")
|
||||||
tick_step = 5
|
ax.set_ylabel("Gaisa temperatūra (Celsija grādos)")
|
||||||
|
ax.set_xlabel("")
|
||||||
plt.yticks(np.arange(min_value, max_value, tick_step))
|
return fig
|
||||||
plt.title("Gaisa temperatūra Rīgā četros gadalaikos")
|
|
||||||
plt.suptitle("")
|
|
||||||
plt.ylabel("Gaisa temperatūra (Celsija grādos)")
|
|
||||||
plt.xlabel("")
|
|
||||||
plt.show()
|
|
||||||
|
|
||||||
|
|
||||||
@logger.catch
|
@logger.catch
|
||||||
def main() -> None:
|
def main() -> None:
|
||||||
# bar_chart()
|
with PdfPages(PDF_PATH) as pdf:
|
||||||
box_plot()
|
fig1 = bar_chart()
|
||||||
|
pdf.savefig(fig1)
|
||||||
|
plt.close(fig1)
|
||||||
|
|
||||||
|
fig2 = box_plot()
|
||||||
|
pdf.savefig(fig2)
|
||||||
|
plt.close(fig2)
|
||||||
|
|
||||||
|
try:
|
||||||
|
system = platform.system().lower()
|
||||||
|
if system == "linux":
|
||||||
|
subprocess.run(["xdg-open", PDF_PATH], check=True)
|
||||||
|
elif system == "windows":
|
||||||
|
subprocess.run(["start", "", PDF_PATH], check=True)
|
||||||
|
elif system == "darwin": # macOS
|
||||||
|
subprocess.run(["open", PDF_PATH], check=True)
|
||||||
|
else:
|
||||||
|
logger.warning(f"Unsupported platform: {system}. Please open the PDF manually.")
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(e)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user