반응형
반응형

[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

반응형
반응형
""" 
정렬 알고리즘 실행 시 비용 계산은 보통 실행 시간(시간 복잡도)이나 작업 횟수를 측정하여 이뤄집니다. 

이를 위해 Python에서 time 모듈이나 timeit 모듈을 사용할 수 있습니다. 

시간 복잡도에 따른 차이

1.퀵 정렬:
    평균 시간 복잡도 𝑂(𝑛log⁡𝑛)O(nlogn).
    큰 데이터셋에서도 효율적으로 작동.

2.버블 정렬:
    최악 및 평균 시간 복잡도 𝑂(𝑛2)O(n 2 ).
    작은 데이터셋에서는 괜찮지만, 데이터 크기가 클수록 비효율적.
    
"""
import time  # 실행 시간 측정을 위한 모듈

# 퀵 정렬 알고리즘
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)

# 버블 정렬 알고리즘
def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

# 테스트 데이터 생성
import random
array_size = 1000  # 데이터 크기
test_array = random.sample(range(1, 10000), array_size)


print(f" test_array : {test_array} \n\n\n")

# 퀵 정렬 실행 시간 측정
start_time = time.time()
quick_sort(test_array.copy())
end_time = time.time()
print(f"퀵 정렬 실행 시간: {end_time - start_time:.5f}초")

# 버블 정렬 실행 시간 측정
start_time = time.time()
bubble_sort(test_array.copy())
end_time = time.time()
print(f"버블 정렬 실행 시간: {end_time - start_time:.5f}초")


# 병합 정렬 알고리즘
def merge_sort(arr):
    if len(arr) <= 1:
        return arr
    mid = len(arr) // 2
    left = merge_sort(arr[:mid])
    right = merge_sort(arr[mid:])
    return merge(left, right)

def merge(left, right):
    result = []
    i = j = 0
    while i < len(left) and j < len(right):
        if left[i] < right[j]:
            result.append(left[i])
            i += 1
        else:
            result.append(right[j])
            j += 1
    result.extend(left[i:])
    result.extend(right[j:])
    return result

# 병합 정렬 실행 시간 측정
start_time = time.time()
merge_sort(test_array.copy())
end_time = time.time()
print(f"병합 정렬 실행 시간: {end_time - start_time:.5f}초")

[python] 정렬 알고리즘 실행 시 비용 계산은 보통 실행 시간(시간 복잡도)이나 작업 횟수를 측정

 

 

 

반응형

'프로그래밍 > Python' 카테고리의 다른 글

[python] Scatter plot animated using python, ffmpeg  (0) 2025.01.16
[python] Happy New year 2025 loop  (0) 2024.12.30
[python] Merry christmas Tree  (0) 2024.12.24
[python] pair plot  (1) 2024.12.20
[python] Generate OTP using python  (1) 2024.12.13
반응형

[python] Happy New year 2025 loop

import time
from random import randint


for i in range(1,85):
    print('')

space = ''


for i in range(1,1000):
    count = randint(1, 100)
    while(count > 0):
        space += ' '
        count -= 1

    if(i%10==0):
        print(space + 'Happy New Year 2025🎉')
    elif(i%9 == 0):
        print(space + "🪅")
    elif(i%5==0):
        print(space +"🎈")
    elif(i%8==0):
        print(space + "🎈")
    elif(i%7==0):
        print(space + "🍁")
    elif(i%6==0):
        print(space + "❤️")
    else:
        print(space + "🔸")

    space = ''
    time.sleep(0.2)
 
반응형
반응형

[python] Merry christmas Tree

import numpy as np
x = np.arange(7,16);
y = np.arange(1,18,2);
z = np.column_stack((x[:: -1],y))
for i,j in z:
    print(' '*i+'*'*j)
for r in range(3):
    print(' '*13, ' || ')
print(' '*12, end = '\======/')    
print('')

               *
              ***
             *****
            *******
           *********
          ***********
         *************
        ***************
       *****************
               ||
               ||
               ||
         \======/

 

반응형
반응형

 

 

python pair plot 

 

데이터 세트의 숫자 변수 간의 쌍 관계를 보여주는 산점도 그리드입니다. 일반적으로 데이터 분포와 변수 간의 관계를 이해하는 데 사용됩니다.

 

import seaborn as sns
import matplotlib.pyplot as plt
import pandas as pd

import sklearn
print(sklearn.__version__)

# Sample dataset (Iris dataset)
from sklearn.datasets import load_iris


iris = load_iris()
df = pd.DataFrame(iris.data, columns=iris.feature_names)
df['species'] = [iris.target_names[i] for i in iris.target]

# Create a pair plot
sns.set(style="ticks")
pairplot = sns.pairplot(df, hue="species", diag_kind="kde")

# Save the pair plot as an image
output_file = "pair_plot.png"
pairplot.savefig(output_file)
print(f"Pair plot saved as {output_file}")

# Show the pair plot
plt.show()

 

반응형
반응형

[VSCODE] 14 VS Code Extensions Every Data Engineer Should Swear By for Maximum Productivity

 

 

1. Jupyter (85M+ downloads)

For Interactive Notebooks and Data Exploration

If you’re working with Python and data science, chances are you’ve used Jupyter notebooks. Well, this extension brings Jupyter functionality directly into VS Code. Whether you’re exploring datasets, running Python scripts, or testing ETL pipelines, this extension allows you to work in an interactive, notebook-style environment without leaving your code editor. It’s perfect for ad-hoc analysis, experimenting with new ideas, and visualizing your data right within your development setup.

Download extension here

 

8. Pylance (118M+ downloads)

For Python IntelliSense and Type Checking

Python is the lingua franca of data engineering, and Pylance supercharges your coding experience with advanced IntelliSense features. It provides type-checking, better autocompletion, and more accurate suggestions, all of which help you write cleaner, more efficient Python code. As a data engineer, you’re likely juggling multiple libraries, so having robust type information can prevent bugs and improve your productivity.

Get extension here

반응형

+ Recent posts