Repository navigation
Expand file tree
/
Copy pathcustom_monthy_chart.py
More file actions
164 lines (151 loc) · 7.14 KB
/
Copy pathcustom_monthy_chart.py
File metadata and controls
164 lines (151 loc) · 7.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
import os
import matplotlib.pyplot as plt
import numpy as np
import tkinter as tk
from io import BytesIO
import csv
import distinctipy
from dateutil.relativedelta import relativedelta
from datetime import datetime
from urllib.request import urlopen
from PIL import Image
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
# Constants
DATA_FILE = './data/data.csv'
CACHE_FOLDER = "./cache"
MINECRAFT_IMAGE_URL = "https://mc-heads.net/avatar/{}" # https://api.mcheads.org/avatar/{}/180
GRAPH_STACKED_BAR = "Stacked bar chart"
GRAPH_LINE = "Line Chart"
GRAPH_BAR = "Bar chart"
GRAPH_PIE = "Pie Chart"
DEFAULT_TYPE = None
AVAILABLE_GRAPH_TYPE = [GRAPH_STACKED_BAR, GRAPH_LINE, GRAPH_BAR, GRAPH_PIE]
SHOW_MINECRAFT_IMAGE = False
FORCE_CLEAR_CACHE = False
def read_csv():
with open(DATA_FILE, 'r', encoding='utf-8') as file:
reader = csv.reader(file, delimiter=';')
# Read header information
title, y_label, x_label = next(reader)[0:3]
start_month = next(reader)
# Read data
categories = []
colors = []
values = []
for row in reader:
categories.append(row[0])
colors.append(row[1] if row[1] != "" else distinctipy.get_random_color(pastel_factor=0.25))
values.append([int(v) for v in row[2:]])
# Ensure all lists have the same length
max_length = max(len(v) for v in values) # Find the longest list
for i in range(len(values)):
values[i] += [0] * (max_length - len(values[i]))
return title, y_label, x_label, start_month[0:max_length] if (len(start_month) > 1 and len(start_month) >= max_length and start_month[1] != "") else start_month[0], categories, colors, values
def generate_months(start_month, num_months):
if isinstance(start_month, list):
return start_month
start_date = datetime.strptime(start_month, "%m-%Y")
return [(start_date + relativedelta(months=i)).strftime("%b %Y") for i in range(num_months)]
def get_minecraft_image(player):
image_path = os.path.join(CACHE_FOLDER, f"{player.replace(" ", "_")}.png")
if not FORCE_CLEAR_CACHE and os.path.exists(image_path):
return Image.open(image_path)
try:
image_url = MINECRAFT_IMAGE_URL.format(player.replace(" ", "_"))
image_byt = urlopen(image_url).read()
image = Image.open(BytesIO(image_byt))
os.makedirs(CACHE_FOLDER, exist_ok = True)
image.save(image_path, "PNG")
print(f"Generated cache image for player '{player}'.")
return image
except Exception as e:
print(f"Image for player '{player}' not found.\nError: {e}")
return None
def select_from_list(options, title = "Select an option"):
result = None # Variable to store the selected option
def on_select(value):
nonlocal result
result = value
root.destroy()
# Create popup window
root = tk.Tk()
root.title(title)
root.geometry("300x" + str(len(options) * 37))
# Create buttons for each option
for option in options:
btn = tk.Button(root, text=option, command=lambda opt=option: on_select(opt))
btn.pack(pady=5, padx=10, fill="x")
# Run the event loop
root.mainloop()
return result
def plot_stacked_bar_chart(ax, months, categories, colors, values):
x = np.arange(len(months))
bottom = np.zeros(len(months))
for category, color, value in zip(categories, colors, values):
ax.bar(x, value, label=category, color=color, bottom=bottom)
bottom += np.array(value)
ax.set_xticks(x)
ax.set_xticklabels(months if not SHOW_MINECRAFT_IMAGE else [(month + (" " * 8)) for month in months])
ax.tick_params(axis='x', rotation=90 if SHOW_MINECRAFT_IMAGE else 45)
if SHOW_MINECRAFT_IMAGE:
for i, month in enumerate(months):
minecraft_image = get_minecraft_image(month)
if minecraft_image:
ax.add_artist(AnnotationBbox(OffsetImage(minecraft_image, zoom=0.1), (x[i], 0), frameon=False, box_alignment=(0.5, 1.5)))
def plot_line_chart(ax, months, values):
total_values = [0] * len(months)
for value in values:
for i, val in enumerate(value):
total_values[i] += val
ax.plot(months, total_values, color="blue", alpha=0.7)
ax.fill_between(months, total_values, color="lightblue", alpha=0.5)
ax.scatter(months, total_values, color="blue", s=50)
def plot_bar_chart(ax, categories, colors, values):
total_values = [sum(value) for value in values]
ax.bar(categories if not SHOW_MINECRAFT_IMAGE else [(category + (" " * 8)) for category in categories], total_values, color=colors)
ax.tick_params(axis='x', rotation=90 if SHOW_MINECRAFT_IMAGE else 45)
if SHOW_MINECRAFT_IMAGE:
for category in categories:
minecraft_image = get_minecraft_image(category)
if minecraft_image:
ax.add_artist(AnnotationBbox(OffsetImage(minecraft_image, zoom=0.1), (category + (" " * 8), 0), frameon=False, box_alignment=(0.5, 1.5)))
def plot_pie_chart(ax, categories, colors, values):
total_values = [sum(value) for value in values]
wedges, texts, junk = ax.pie(total_values, labels=categories if not SHOW_MINECRAFT_IMAGE else [((" " * 4) + category + (" " * 4)) for category in categories], autopct=(lambda val: str(round(val / 100 * sum(total_values)))), startangle=0, colors=colors)
# Add images next to each label
if SHOW_MINECRAFT_IMAGE:
for i, category in enumerate(categories):
minecraft_image = get_minecraft_image(category)
if minecraft_image:
# Calculate position for annotation based on wedge angle
angle = (wedges[i].theta2 - wedges[i].theta1) / 2. + wedges[i].theta1
x = np.cos(np.radians(angle)) * 1.1
y = np.sin(np.radians(angle)) * 1.1
# Add image next to label
ab = AnnotationBbox(OffsetImage(minecraft_image, zoom=0.1), (x, y), frameon=False, box_alignment=(0.5, 0.5))
ax.add_artist(ab)
def show_chart(chart_type, show_select = True):
if chart_type in AVAILABLE_GRAPH_TYPE:
title, y_label, x_label, start_month, categories, colors, values = read_csv()
fig, ax = plt.subplots(figsize=(10, 6))
fig.canvas.manager.set_window_title(title)
ax.set_title(title)
ax.set_ylabel(y_label)
ax.set_xlabel(x_label)
ax.yaxis.get_major_locator().set_params(integer=True)
if chart_type == GRAPH_STACKED_BAR:
plot_stacked_bar_chart(ax, generate_months(start_month, len(values[0])), categories, colors, values)
ax.legend()
elif chart_type == GRAPH_LINE:
plot_line_chart(ax, generate_months(start_month, len(values[0])), values)
elif chart_type == GRAPH_BAR:
plot_bar_chart(ax, categories, colors, values)
elif chart_type == GRAPH_PIE:
plot_pie_chart(ax, categories, colors, values)
ax.get_xaxis().set_visible(False)
ax.get_yaxis().set_visible(False)
plt.tight_layout()
plt.show()
elif show_select:
return show_chart(select_from_list(AVAILABLE_GRAPH_TYPE, "Select a chart type"), False)
show_chart(DEFAULT_TYPE)