Created
June 25, 2021 09:44
-
-
Save jinhangjiang/06b1ca78a6d6c70d2cebe7f18c2b9c20 to your computer and use it in GitHub Desktop.
Visualize High-Dimensional Network Data with 3D Scatter Plot
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def ThreeDplot(model): | |
"Creates TSNE model and plots it" | |
"Get the labels and vectors from ndoe2vec mode" | |
labels = [] | |
tokens = [] | |
for word in model.wv.vocab: | |
tokens.append(model[word]) | |
labels.append(word) | |
"Index the label table and prepare for annotating the graph" | |
lab = [] | |
for i in labels: | |
lab.append(label[label.Vertex==i].values[0][1]) | |
"make a tsne model, set n_components = 3 which will reduce the size of dimensions to 3." | |
tsne_model = TSNE(perplexity=10, n_components=3, learning_rate=20, init='random', n_iter=1000, random_state=42) | |
new_values = tsne_model.fit_transform(tokens) | |
x = [] | |
y = [] | |
z = [] | |
for value in new_values: | |
x.append(value[0]) | |
y.append(value[1]) | |
z.append(value[2]) | |
"create 3D scatter plot with seaborn and matlibplot" | |
sns.set_style("whitegrid", {'axes.grid' : False}) | |
fig = plt.figure(figsize=(20, 15)) | |
ax = Axes3D(fig) | |
gist_ncar = cm.get_cmap('gist_ncar', len(set(lab))) | |
ax.scatter(x, y, z, c=lab, cmap=gist_ncar, marker='o',alpha=0.7,s=200) | |
ax.set_xlabel('X Label') | |
ax.set_ylabel('Y Label') | |
ax.set_zlabel('Z Label') | |
"annotating the graph" | |
for x_label, y_label, z_label, label_node in zip(x, y, z, lab): | |
ax.text(x_label, y_label, z_label, label_node) | |
## 360 degree view | |
def rotate(angle): | |
ax.view_init(azim=angle) | |
"configure paths, specifically for Google Colab; use 'pillow' as writer instead of 'imagemagick' " | |
rc('animation', html='jshtml') | |
rot_animation = animation.FuncAnimation(fig, rotate, frames=np.arange(0,362,2),interval=100) | |
rot_animation.save('rotation.gif', dpi=40, writer='pillow') | |
rot_animation |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment