-
Notifications
You must be signed in to change notification settings - Fork 14
/
cluster_plotter.py
179 lines (154 loc) · 5.58 KB
/
cluster_plotter.py
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
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
import time
import numpy as np
import pandas as pd
import matplotlib
import matplotlib.pyplot as plt
import datetime
import settings
# import plotly.plotly as py
# import plotly.graph_objs as go
class ClusterPlotter(object):
"""Matplotlib plotter plots bubble clusters"""
def __init__(self):
pass
def update_annot(self, ind):
index = ind["ind"][0]
pos = self.sc.get_offsets()[index]
self.annot.xy = pos
text = self.names[index]
self.annot.set_text(text)
self.annot.set_bbox(dict(facecolor='blue', alpha=0.15))
self.annot.set_family("sans-serif")
self.annot.set_color("black")
def hover(self, event):
vis = self.annot.get_visible()
if event.inaxes == self.ax:
cont, ind = self.sc.contains(event)
if cont:
self.update_annot(ind)
self.annot.set_visible(True)
self.fig.canvas.draw_idle()
else:
if vis:
self.annot.set_visible(False)
self.fig.canvas.draw_idle()
def plot(self, x, y, sizes, text, plot_at):
self.x = np.array(x)
self.y = np.array(y)
self.z = np.array(sizes)
self.names = np.array(text)
self.fig = plt.figure(3, figsize=(10,8), facecolor="white", edgecolor="black")
self.ax = plt.gca()
plt.subplots_adjust(left=0.15, bottom=0.13)
plt.title("Crypto bursting items at "+str(plot_at),
fontdict={"fontsize":14, "fontweight":2}, weight="bold",
fontname='Sans', color = "black")
plt.xlabel('Creation time [UTC]', size=12, fontname='Sans', color = "black")
plt.ylabel('Last activity [UTC]', size=12, fontname='Sans', color = "black")
plt.xticks(rotation=30, size=12, color="black")
plt.yticks(size=12, color="black")
self.ax.set_facecolor("white")
xmax = max(x)
xmin = min(x)
deltax = (xmax-xmin)/10
plt.xlim(left=xmin-deltax, right=xmax+deltax)
ymax = max(y)
ymin = min(y)
deltay = (ymax-ymin)/10
plt.ylim(bottom=ymin-deltay, top=ymax+deltay)
# hfmt = matplotlib.dates.DateFormatter('%H:%M:%S')
hfmt = matplotlib.dates.DateFormatter('%d-%m %H:%M')
self.ax.xaxis.set_major_formatter(hfmt)
self.ax.yaxis.set_major_formatter(hfmt)
# s regulates size, c regulate color
self.sc = plt.scatter(self.x, self.y, s=self.z*10, c=self.z,
cmap="Blues", alpha=0.4, edgecolors="grey", linewidths=2)
self.annot = plt.annotate('text',
xycoords='data', xy=(3, 1),
textcoords='axes fraction', xytext=(0.1, 0.2),
bbox=dict(boxstyle="round", fc="w"),
arrowprops=dict(facecolor='black', arrowstyle='fancy'))
self.annot.set_visible(False)
self.fig.canvas.mpl_connect("motion_notify_event", self.hover)
plt.show()
# class ClusterPlotlyPlotter(object):
# """plotly plotter plots bubble clusters"""
# def __init__(self):
# pass
# def plot(self, x, y, sizes, text, plot_at):
# sizes = np.array(sizes)
# trace = go.Scatter(
# x=x,
# y=y,
# text=text,
# mode='markers',
# marker=dict(
# opacity='size',
# size=sizes,
# sizemode='area',
# sizeref=2.*max(sizes)/(30.**2),
# sizemin=4,
# color = 'rgba(0, 0, 152, .8)',
# line = dict(
# width = 1,
# color = 'rgb(0, 0, 0, .2)'
# )
# )
# )
# layout = go.Layout(
# title='Crypto bursting items at '+str(plot_at),
# xaxis=dict(
# title='Creation time',
# # gridcolor='rgb(255, 255, 255)',
# # # range=[2.003297660701705, 5.191505530708712],
# # # # type='log',
# # zerolinewidth=1,
# # ticklen=5,
# # gridwidth=2,
# ),
# yaxis=dict(
# title='Last activity',
# # gridcolor='rgb(255, 255, 255)',
# # # range=[36.12621671352166, 91.72921793264332],
# # zerolinewidth=1,
# # ticklen=5,
# # gridwidth=2,
# ),
# paper_bgcolor='rgb(243, 243, 243)',
# plot_bgcolor='rgb(243, 243, 243)',
# )
# fig = go.Figure(data=[trace], layout=layout)
# py.plot(fig, filename='items-cluster')
def main():
# borrar siguiente linea para cerrar el programa al cerrar la grafica
while not plt.fignum_exists(1):
try:
clusters = pd.read_csv(settings.active_clusters_csv)
except:
pass
else:
clusters["created_at"] = clusters["created_at"].apply(lambda x: (pd.to_datetime(x)))
clusters["last_activity"] = clusters["last_activity"].apply(lambda x: (pd.to_datetime(x)))
legends = []
for _, cluster in clusters.iterrows():
root_item = str(cluster.root_item)
n=70
if len(root_item)>n:
root_item = root_item[:n+root_item[n:].find(" ")]+"\n"+root_item[n+root_item[n:].find(" ")+1:]
terms = str(cluster.terms)
if len(terms)>n:
terms = terms[:n+terms[n:].find(" ")]+"\n"+terms[n+terms[n:].find(" ")+1:]
legends.append("Cluster ID: "+str(cluster.id)+"\nitems: "+
str(cluster.n_items)+"\nTerms: "+terms+
"\nRoot item: "+root_item+
"\nRoot_user: "+str(cluster.root_user)+
"\nRoot_followers: "+str(cluster.root_followers)+
"\nRoot_user_created_at: "+str(cluster.root_user_created_at)+
"\nOther: "+str(cluster.other_items[:300]+"..."))
plotter = ClusterPlotter()
plotter.plot(x=clusters["created_at"], y=clusters["last_activity"],
sizes=1*clusters["n_items"],
text=legends,
plot_at=str(datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S UTC %Y")))
if __name__ == '__main__':
main()