Pythonでグラフィックを描く

28006 ワード

テーブル列データ
Heatmap
カテゴリデータ
数値データ

モジュールインポート、データの定義

import matplotlib.pyplot as plt
%matplotlib inline

subject = ['English', 'Math', 'Korean', 'Science', 'Computer']
points = [40, 90, 50, 60, 100]
fig = plt.figure(figsize=(5,2)) # 그래프사이즈 조절
ax1 = fig.add_subplot(1,1,1)

fig = plt.figure()
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,4)

APIドキュメント:https://matplotlib.org/stable/api/index.html
https://matplotlib.org/stable/api/figure_api.html?highlight=add_subplot#matplotlib.figure.Figure.add_subplot
https://matplotlib.org/stable/api/figure_api.html?highlight=figure#module-matplotlib.figure
# 그래프 데이터 
subject = ['English', 'Math', 'Korean', 'Science', 'Computer']
points = [40, 90, 50, 60, 100]

# 축 그리기
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

# 그래프 그리기
ax1.bar(subject, points)

# 라벨, 타이틀 달기
plt.xlabel('Subject')
plt.ylabel('Points')
plt.title("Yuna's Test Result")

直線図を描く

from datetime import datetime
import pandas as pd
import os

# 그래프 데이터 
csv_path = os.getenv("HOME") + "/data_visualization/data/AMZN.csv"
data = pd.read_csv(csv_path ,index_col=0, parse_dates=True)
price = data['Close'] #Pandas Series 선그래프 그리기 기능
print(price)
# 축 그리기 및 좌표축 설정
fig = plt.figure()
ax = fig.add_subplot(1,1,1)

#Pandas plot사용 하면서 matplotlib정의한 subplot공간 ax사용
price.plot(ax=ax, style='black')

plt.ylim([1600,2200]) # 좌표축 설정
plt.xlim(['2019-05-01','2020-03-01'])

# 주석달기 (그래프 안에 추가적으로 글자나 화살표 주석 그릴때 annotate()메소드 사용)
important_data = [(datetime(2019, 6, 3), "Low Price"),(datetime(2020, 2, 19), "Peak Price")]
for d, label in important_data:
    ax.annotate(label, xy=(d, price.asof(d)+10), # 주석을 달 좌표(x,y)
                xytext=(d,price.asof(d)+100), # 주석 텍스트가 위차할 좌표(x,y)
                arrowprops=dict(facecolor='red')) # 화살표 추가 및 색 설정

# 그리드, 타이틀 달기
plt.grid() # 격자눈금 추가
ax.set_title('StockPrice')

# 보여주기
plt.show()

plot用法詳細


グラフィック()オブジェクトを作成し、add subflot()を使用してサブマップを作成し、plotを描画します.
2つのプロセスを省略しますplt.plot()コマンドを使用してグラフィックを描画する場合、matplotlibは**가장 최근의 figure객체의 서브플롯을 그린다. 만약 서브 플롯이 없으면 서브플롯을 하나 생성한다.**
import numpy as np
x = np.linspace(0, 10, 100) #0에서 10까지 균등한 간격으로  100개의 숫자를 만들라는 뜻입니다.
plt.plot(x, np.sin(x),'o')
plt.plot(x, np.cos(x),'--', color='black') 
plt.show()

#------------------------------------------
x = np.linspace(0, 10, 100) 

plt.subplot(2,1,1)
plt.plot(x, np.sin(x),'orange','o')

plt.subplot(2,1,2)
plt.plot(x, np.cos(x), 'orange') 
plt.show()

x = np.linspace(0, 10, 100) 

plt.plot(x, x + 0, linestyle='solid') 
plt.plot(x, x + 1, linestyle='dashed') 
plt.plot(x, x + 2, linestyle='dashdot') 
plt.plot(x, x + 3, linestyle='dotted')
plt.plot(x, x + 0, '-g') # solid green 
plt.plot(x, x + 1, '--c') # dashed cyan 
plt.plot(x, x + 2, '-.k') # dashdot black 
plt.plot(x, x + 3, ':r'); # dotted red
plt.plot(x, x + 4, linestyle='-') # solid 
plt.plot(x, x + 5, linestyle='--') # dashed 
plt.plot(x, x + 6, linestyle='-.') # dashdot 
plt.plot(x, x + 7, linestyle=':'); # dotted

Pandas plot()グラフィックを描画

  • label:グラフィックの凡例名.
  • ax:図形描画用matplotlibのサブ印刷対象.
  • style:matplotlibに渡される「ko-」と同じパターンの文字列
  • alpha:透明度(0-1)
  • kind:図形のタイプ:line、bar、barh、kde
  • ology:Y軸のログ規模
  • use index:ルーラー名としてオブジェクトのインデックスを使用するか
  • rot:回転目盛り名称(0~360)
  • xticks,yticks:x軸、y軸使用値
  • xlim,ylim:x軸,y軸限界
  • grid:軸のグリッドを表示するか
  • PandasのデータがDataFrameの場合のplotメソッドパラメータ

  • サブブロック:各DataFrameのコラムを独立したサブマップに描く.
  • sharex:サブブロック=X軸(例えばTrue面)を共有し、ルーラーと境界を接続します.
  • sharey:サブブロック=実面を共有するY軸.
  • figsize:図形の大きさ、tuple指定
  • title:グラフィックタイトルを文字列に指定
  • sort columns:アルファベット順にコラムを書く.
  • fig, axes = plt.subplots(2, 1)
    data = pd.Series(np.random.rand(5), index=list('abcde'))
    data.plot(kind='bar', ax=axes[0], color='blue', alpha=1)
    data.plot(kind='barh', ax=axes[1], color='red', alpha=0.3)
    
    #--------------------------------------------
    
    df = pd.DataFrame(np.random.rand(6,4), columns=pd.Index(['A','B','C','D']))
    df.plot(kind='line')

  • fig = plt.図():対象宣言「展開図画紙」
  • axl = flg.addサブブロック(1,1):描画軸
  • axl.bar(x,y)軸内で描画するグラフィックの方法を選択し、パラメータとしてデータを追加
  • グラフィックタイトル軸のラベルなど、pltの様々な方法grid、xlabel、ylabel、使用添加
  • plt.saveflgメソッドを使用して保存します.