Skip to content
mahler83 blog v2

Pharmacology, IoT, LLMs

mahler83 blog v2

Pharmacology, IoT, LLMs

Rotating 3D t-SNE animated gif scatterplot with matplotlib

mahler83, 2019-10-112023-07-19

So I’ve been through a few hours of searching + trial & error and came up with a simple solution to draw an animated GIF 3D scatterplot.
(minimum library installs, exclude bash commands)

X = data.iloc[:,0:-1]
Y = data.iloc[:,-1].astype('int')

from sklearn.manifold import TSNE
tsne = TSNE(n_components=3, random_state=RS, perplexity=10)
tsne_fit = tsne.fit_transform(X)

n_components should be set to 3 in order to draw a 3D plot.
perpliexity should be adjusted by trial and error to find the best value that represents your data. sqrt(N) is a good starting point.

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import animation
fig = plt.figure(figsize=(10,10))
ax = Axes3D(fig)
colors = 'b', 'r'
labels = 'Group1', 'Group2'

for i, c, label in zip(range(len(labels)), colors, labels):
    ax.scatter(tsne_fit[data['Group']==i, 0], tsne_fit[data['Group']==i, 1], tsne_fit[data['Group']==i, 2], s=30, c=c, label=label, alpha=0.5)
fig.legend()

Axes3D is for 3D plotting.
matplotlib.animation is for making animated GIF.

Draw the scatterplot. In my case, I used scatter() twice to label the outcome feature.
Added alpha=0.5 for better visualization when datapoints overlap.

def rotate(angle):
     ax.view_init(azim=angle)

angle = 3
ani = animation.FuncAnimation(fig, rotate, frames=np.arange(0, 360, angle), interval=50)
ani.save('inhadr_tsne1.gif', writer=animation.PillowWriter(fps=20))

Build an arbitrary function rotate() that updates the view of the plot. This function will be called by FuncAnimation().
The writer is set to PillowWriter since it’s included by default in matplotlib. But while searching, I found that in some cases there are some problems in the animation, and can be solved by using a different writer, such as FFMpegWriter.
angle=3 means the plot rotates 3 degrees every frame. (120 frames in total)
interval=50, fps=20 values can be tweaked to change the rotation speed of animation.

bingle bangle~

Took 10 seconds to draw this.
대만족! This is definitely going to be put in my next presentation!

Share this:

  • Twitter
  • Facebook
IT Lab Stuff Tips & Techs

Post navigation

Previous post
Next post

Related Posts

Nanodrop에서 DNA 측정시 A260/280, A260/230의 의미

2013-05-012013-11-22

기본적으로 DNA는 260nm에서 최대 흡광도를 가진다. 가장 많이 쓰이는 지표인 A260/280은 DNA에서 1.8, RNA에서 2.0 이상이면 pure하다고 본다. A260/230은 2.0-2.2 이상이면 pure하다고 본다. 너무 높으면 기기 오류나 샘플에 문제가 있는 경우이므로 무조건 높다고 좋은 게 아님! 각각의 nucleotide가 가지는 흡광도는 다음과 같다. A 4.50 T 1.47 G 1.15 C 1.51…

Share this:

  • Twitter
  • Facebook
Read More
IT

엑셀 애니메이션 효과 끄기

2016-09-232023-07-19

엑셀에서 화살표로 셀 사이를 움직이는 등 동작을 할 때 반응이 바로바로 오지 않고 멋드러지게 애니메이션 효과를 넣어주는 것이 불편해서 OS설정을 다음과 같이 변경해봤다. 윈도우키+u 좌측 기타옵션 “시각적 옵션” 중의 첫 번째 항목인 “Windows에서 애니메이션 재생”을 끔으로 설정 이렇게 간단하게 윈10 전반적으로 불편하게 느껴지던 애니메이션이 모두 사라졌다. 오예~

Share this:

  • Twitter
  • Facebook
Read More
Gaming

샤오미폰 포켓몬고 듀얼앱 구글 계정 추가하는 방법

2018-09-102018-09-11

샤오미 폰에서 듀얼앱으로 포켓몬고를 2계정 돌리는 것이 가능하고, 여기에 포켓몬고 플러스도 2개 연결해서 사용 가능하다. 문제는 복제된 포켓몬고에 계정을 추가하려고 하면 이미 추가된 계정이라고 오류가 뜨는 것이다. (계정 추가가 복제된 시스템이 아니라 본 시스템에 이루어지는 문제) 이럴 때 다음과 같이 구글 플레이 게임을 복제해서 복제된 시스템에 구글 계정을 추가해주면 된다….

Share this:

  • Twitter
  • Facebook
Read More

Comments (4)

  1. S C says:
    2021-06-22 at 19:11

    Exactly what I was looking for!

    Reply
    1. mahler83 says:
      2021-07-04 at 12:49

      Glad to hear my post helped!

  2. Ramses Alexander Coraspe Valdez says:
    2021-09-08 at 10:50

    Does it work with option ax.text(x,y,x, text)?

    Reply
    1. mahler83 says:
      2021-09-08 at 15:23

      Sorry, I’ve never tried annotation.
      Does this help?
      https://stackoverflow.com/questions/56293154/axes3d-text-annotate-3d-scatter-plot

Leave a Reply to Ramses Alexander Coraspe Valdez Cancel reply

Your email address will not be published. Required fields are marked *

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
  1. mahler83 on 공부 잘하는 과학적 방법 – Weinstein 2018.12023-07-30

    접속자가 갑자기 늘어서 홈페이지가 오동작을 했습니다. 시간이 지나면 나아질 것 같습니다.

  2. SkyHigh on 공부 잘하는 과학적 방법 – Weinstein 2018.12023-07-30

    PC에선 잘 보이는데 모바일(아이폰)에선 한번 보이고 이후부턴 계속 나오질 않네요. 뭔가 문제가 있어보입니다. 한번 확인해봐주세요

  3. mahler83 on DadGPT 한자능력검정시험 교재 4급II (자체제작)2023-07-19

    참고로 이번 주가 어문회 시험 신청 기간입니다. 좋은 결과 있으시길!

  4. Jin on DadGPT 한자능력검정시험 교재 4급II (자체제작)2023-07-19

    감사합니다~ 어이 말고 재가 해야 겠어요~

  5. mahler83 on GPT에게 한의사 국시를 풀게 했더니 57% 정답률 – 2023.32023-06-14

    안녕하세요, 댓글이 스팸필터에 걸려있어 뒤늦게 확인했습니다. 트위터에서 멘션이나 DM주셔도 되는데 번거로운 방식을 선택하신 이유가 궁금하네요. 일단 메일 드리겠습니다.

  • 3D Printing
  • Academic writing
  • Adsense
  • AI
  • AWS
  • Creativity
  • DIY
  • favorites
  • Gaming
  • Generative AI
  • hands-on
  • Home Assistant
  • Ideas
  • IT
  • Lab Stuff
  • Large language model
  • Law
  • Machine Learning
  • Medical Education
  • Medicine
  • My Thoughts
  • Neuroscience
  • Parenting
  • Pedagogy
  • Pharmacology
  • PHP
  • PokemonGo
  • Precision medicine
  • Reasoning
  • Science
  • Social studies
  • Statistics and Math
  • Tips & Techs
  • Twitter API
  • Ubuntu
  • Uncategorized
  • Web development
  • Web News
©2023 mahler83 blog v2 | WordPress Theme by SuperbThemes