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

IT

구글 드라이브를 이용해 공짜로 OCR 사용하기

2016-04-252016-04-25

책의 일부분 텍스트가 필요해 해당 페이지를 pdf로 스캔했다. 예전에 구글 드라이브가 OCR기능을 제공한다는 이야기를 들은 기억이 나서 한 번 시도해봤다. 이것저것 해보다가 다행히 성공…^^ How to use Google Docs as a free OCR tool  우선 필요한 부분을 스냅샷(사진기) 툴로 복사한다.   2. 그림판 등을 이용해 그림파일로 저장. 3. 구글 드라이브에…

Share this:

  • Twitter
  • Facebook
Read More

Some useful numbers for plasmid DNA extraction

2013-05-012013-11-22

GFP plasmid DNA 뽑으면서 궁금했던 것들을 찾아서 정리해봤다. Optimal Optical Density at 600nm (OD600) for plasmid DNA extraction = 2~4 – This is the log growth phase OD600 = 1 → 1.6 x 10 ^ 9 cells / mL – correlation of cell count and optical density 1 x 10…

Share this:

  • Twitter
  • Facebook
Read More

“실온”은 실험용 쥐에게 정상적인 환경이 아닐수도 있다.

2013-11-202023-07-19

  흔히 실험용 mouse나 rat을 20~26℃의 “실온”에서 키우게 되는데, 이 온도에서 쥐의 면역반응이 떨어질 수 있다는 연구결과가 나왔다. 30-31도의 따뜻한 온도에서 사육할 경우  tumor formation, growth rate, metastasis 등이 감소했다는 연구. 실험동물 사육 환경의 표준이 흔들릴만한 의미 있는 연구 결과이다. 참고기사: http://www.nature.com/news/chilly-lab-mice-skew-cancer-studies-1.14190 참고논문: http://www.ncbi.nlm.nih.gov/pubmed/24248371

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 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