반응형
반응형

[python] Scatter plot animated using python, ffmpeg

 

""" 
An animated scatter plot can be created using Python's matplotlib library with its animation module. 
Here's an example of how to create an animated scatter plot, where points move dynamically over time.
"""

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation

# Generate random initial data for the scatter plot
num_points = 50
x_data = np.random.rand(num_points)
y_data = np.random.rand(num_points)
colors = np.random.rand(num_points)
sizes = np.random.rand(num_points) * 100

# Function to update scatter plot
def update(frame):
    global x_data, y_data
    x_data += (np.random.rand(num_points) - 0.5) * 0.1  # Randomly move x
    y_data += (np.random.rand(num_points) - 0.5) * 0.1  # Randomly move y
    scatter.set_offsets(np.c_[x_data, y_data])  # Update positions
    scatter.set_sizes(np.random.rand(num_points) * 100)  # Update sizes
    scatter.set_array(np.random.rand(num_points))  # Update colors
    return scatter,

# Create the figure and scatter plot
fig, ax = plt.subplots()
scatter = ax.scatter(x_data, y_data, c=colors, s=sizes, cmap='viridis', alpha=0.6)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
ax.set_title("Animated Scatter Plot")

# Create animation
ani = FuncAnimation(fig, update, frames=100, interval=50, blit=True)

# Show the animation
plt.show()

import matplotlib.animation as animation
animation.FFMpegWriter = animation.writers['ffmpeg']

""" 
Install FFmpeg: FFmpeg is required to save animations in video formats like .mp4. Install it as follows:

Windows:

Download the FFmpeg executable from https://ffmpeg.org/download.html.
Add the bin folder to your system’s PATH environment variable.

1.EXE  파일 다운받아서  *.7z 파일 다운로드. 

2.압축 풀고,  시스템 환경 변수에 추가. 

3.  ffmpeg -version  으로 실행되는지 확인 

"""

ani.save("animated_scatter.mp4", writer="ffmpeg", fps=30)  # Save as MP4

반응형
반응형

Gensim word vector visualization of various word vectors

web.stanford.edu/class/cs224n/materials/Gensim%20word%20vector%20visualization.html

 

Gensim word vector visualization

For looking at word vectors, I'll use Gensim. We also use it in hw1 for word vectors. Gensim isn't really a deep learning package. It's a package for for word and text similarity modeling, which started with (LDA-style) topic models and grew into SVD and n

web.stanford.edu

import numpy as np

# Get the interactive Tools for Matplotlib
%matplotlib notebook
import matplotlib.pyplot as plt
plt.style.use('ggplot')

from sklearn.decomposition import PCA

from gensim.test.utils import datapath, get_tmpfile
from gensim.models import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec
 
glove_file = datapath('/Users/manning/Corpora/GloVe/glove.6B.100d.txt')
word2vec_glove_file = get_tmpfile("glove.6B.100d.word2vec.txt")
glove2word2vec(glove_file, word2vec_glove_file)
model = KeyedVectors.load_word2vec_format(word2vec_glove_file)
model.most_similar('obama')
model.most_similar('banana')
model.most_similar(negative='banana')
result = model.most_similar(positive=['woman', 'king'], negative=['man'])
print("{}: {:.4f}".format(*result[0]))
def analogy(x1, x2, y1):
    result = model.most_similar(positive=[y1, x2], negative=[x1])
    return result[0][0]
Analogy

analogy('japan', 'japanese', 'australia')
analogy('australia', 'beer', 'france')
analogy('obama', 'clinton', 'reagan')
analogy('tall', 'tallest', 'long')
analogy('good', 'fantastic', 'bad')
print(model.doesnt_match("breakfast cereal dinner lunch".split()))
 
def display_pca_scatterplot(model, words=None, sample=0):
    if words == None:
        if sample > 0:
            words = np.random.choice(list(model.vocab.keys()), sample)
        else:
            words = [ word for word in model.vocab ]
        
    word_vectors = np.array([model[w] for w in words])

    twodim = PCA().fit_transform(word_vectors)[:,:2]
    
    plt.figure(figsize=(6,6))
    plt.scatter(twodim[:,0], twodim[:,1], edgecolors='k', c='r')
    for word, (x,y) in zip(words, twodim):
        plt.text(x+0.05, y+0.05, word)
 
display_pca_scatterplot(model, 
                        ['coffee', 'tea', 'beer', 'wine', 'brandy', 'rum', 'champagne', 'water',
                         'spaghetti', 'borscht', 'hamburger', 'pizza', 'falafel', 'sushi', 'meatballs',
                         'dog', 'horse', 'cat', 'monkey', 'parrot', 'koala', 'lizard',
                         'frog', 'toad', 'monkey', 'ape', 'kangaroo', 'wombat', 'wolf',
                         'france', 'germany', 'hungary', 'luxembourg', 'australia', 'fiji', 'china',
                         'homework', 'assignment', 'problem', 'exam', 'test', 'class',
                         'school', 'college', 'university', 'institute'])
display_pca_scatterplot(model, sample=300)
반응형
반응형

matplotlib의 scatter 만들기 . 그래프


Scatter Plots in Python  https://plot.ly/python/line-and-scatter/
reference : https://plot.ly/python/reference/#scatter


plot 버전 체크  


>>import plotly
>>plotly.__version__



scatter 만들기


import plotly.plotly as py

import plotly.graph_objs as go


# Create random data with numpy

import numpy as np


N = 1000

random_x = np.random.randn(N)

random_y = np.random.randn(N)


# Create a trace

trace = go.Scatter(

    x = random_x,

    y = random_y,

    mode = 'markers'

)


data = [trace]


# Plot and embed in ipython notebook!

py.iplot(data, filename='basic-scatter')


# or plot with: plot_url = py.plot(data, filename='basic-line')



...


반응형

+ Recent posts