카테고리 없음

[Python] matplot 시각화 모듈 - 히스토그램

byeolsub 2023. 4. 25. 13:08

📌

# 자동차 연비데이터의 mpg 값을 히스토그램으로 출력하기
import seaborn as sns
df = sns.load_dataset("mpg")
import matplotlib.pyplot as plt
plt.style.use("ggplot") # 그래프의 style 설정
plt.rc('font', family="Malgun Gothic") # 한글폰트 설정
df.info()

# 히스토그램으로 출력
df["mpg"].plot(kind="hist")

# 간격을 20개로 분리하여 히스토그램으로 출력
#1 (그래프에서 막대 사이 간격이 나올때)
df["mpg"].plot(kind="hist",bins=20,color='coral',figsize=(10,5),
               edgecolor='white')
plt.title("MPG 히스토그램")
plt.xlabel("mpg(연비)")

#2 (그래프에서 막대 사이 간격이 안나올때)
df["mpg"].plot(kind="hist",bins=20,color='coral',figsize=(10,5),
               linewidth=1)
plt.title("MPG 히스토그램")
plt.xlabel("mpg(연비)")

# 히스토그램으로 출력 df["mpg"].plot(kind="hist")

# weight,mpg 데이터의 산점도 출력하기
# DataFrame.plot(kind="scatter") : 그래프의 종류
# x='mpg' : x축의 사용될 컬럼명
# y='weight' : y축의 사용되 컬럼명
# s=50 : 점의 크기 지정
df.plot(kind='scatter',x='mpg',y='weight', c='coral',
        s=50, figsize=(10,5))

# matpolt 모듈을 이용하여 산점도 출력하기
plt.figure(figsize=(10,5)) # 새로운 그래프 창 오픈
# scatter(x축 데이터, y축 데이터) : 그래프 종류. 산점도
# df["mpg"] : x축 데이터값
# df["weight"] : y축 데이터값
plt.scatter(df["mpg"],df["weight"],c="coral",s=20)

df.plot(kind='scatter',x='mpg',y='weight', c='coral',s=50, figsize=(10,5))

df[["mpg","weight"]].corr()
df[["mpg","cylinders"]].corr()

# bubble 그래프 : 산점도. 점의 크기를 데이터의 값으로 결정
# 3개의 컬럼 지정 : x축 : weight, y축 : mpg , 점의 크기 : cylinders
# cylinders의 데이터의 값의 종류와 갯수 조회
df["cylinders"].unique() # 결과 -> array([8, 4, 6, 3, 5], dtype=int64)
df["cylinders"].value_counts()

# cylinders 값을 최대값의 비율로 계산하여 데이터 생성
cylinders_size = (df["cylinders"]/df["cylinders"].max() * 100)
cylinders_size.value_counts()
# alpha=0.7 : 점의 색을 반투명하게(약 70% 정도) 표시 - 겹쳐진 부분을 확인하기 위해
df.plot(kind='scatter',x='weight',y='mpg', c='coral',
        s=cylinders_size, figsize=(10,5), alpha=0.7)

# 색상값을 가지고 데이터 값을 설정.
# marker="+" : 산전도 점의 모양
# cmap="magma": mapplot 모듈에서 숫자에 해당하는 색의 목록
#    viridis, inferno, magma, cividis,...
# c=df["cylinders"] : cylinders의 값에 해당하는 색을 cmap에서 선택
df.plot(kind="scatter",x="weight",y="mpg",marker="+",figsize=(10,5),
        cmap="magma",c=df["cylinders"],s=50,alpha=0.7)
plt.title("산점도:mpg-weight-cylinders")
# transparent=True : 투명그림으로 저장
plt.savefig("scatter_transparent.png",transparent=True)