コンテンツにスキップ

Matplot/Seaborn Basic

表示基本設定

sns.set(font_scale=1.1)
sns.set_style('white')
fig =plt.figure (figsize = (30,5))
plt.figure (figsize = (8,8))

複数グラフの描画

congress80_dem = congress80[congress80['party'] == 'Democrat'].copy()
congress80_rep  =congress80[congress80['party'] == 'Republican'].copy()

#グラフの描画範囲を設定する
fig, ax = plt.subplots()
plt.xlim(-1.5, 2)
plt.ylim(-1.5, 1.5)
# Democratの散布図を作る
plt.scatter(congress80_dem['dwnom1'], congress80_dem['dwnom2'], c = "r", alpha = 0.3)
# Republicanの散布図を作る
plt.scatter(congress80_rep['dwnom1'], congress80_rep['dwnom2'], c = "b", alpha = 0.3)

相関係数の可視化

train_df.corr().style.background_gradient(axis=None)

列に項目別のグラフを同時に表示する

sns.relplot(data = ASFR_graph, x = 'age', y = 'ASFR', col = "period", hue = 'country', kind = 'line')

x軸ラベルの回転

fig, ax = plt.subplots(figsize = (10,10)) 
sns.boxplot(x= 'home', y = 'y', data = train_new)
labels = ax.get_xticklabels() 
plt.setp(labels, rotation=90);

ヒストグラムの表示(複数グラフを重ねて表示)

sns.distplot(df["Temperature"],bins=20,label = "2018")
sns.distplot(df["Temperature"],bins=20,label = "2019")

plt.legend(loc =0)
plt.title("Temperature")
sns.despine(left=True)

ヒストグラムの表示(横に並べて表示)

sns.set(font_scale=1.1)
sns.set_style('white')
fig =plt.figure (figsize = (30,5))

temp = ['temp_0',"temp_1","temp_2"]

for i in range(len(temp)):
    le = fig.add_subplot(1,3,i+1)
    sns.distplot(df[temp[i]],bins=20)
    plt.title("Temperature")
    sns.despine(left=True)

散布図の表示(横に表示/基準線の表示)

sns.set(font_scale=1.3)
sns.set_style('white')
sns.set_style( {"xtick.major.size":8,"ytick.major.size":8})

g = sns.FacetGrid(df, col="GROUP", height=8, legend_out=True)
g.map_dataframe(sns.scatterplot,x="ratio",y="temp",hue = "GROUP")
g.set_titles(col_template="{col_name}", row_template="{row_name}")
g.set( xlim=(4, 10),ylim=(-150, -140),xlabel="label",ylabel="label")
g.add_legend()

# HMBの値破線記載
for (row_val), ax in g.axes_dict.items():
       ax.axhline(y=5, linestyle='--',color = "r"), ax.axvline(x=5, linestyle='--',color = "r")

時系列データの表示関数

def point_view(df):

    sns.set(font_scale=1.3)
    #sns.set_style('white')
    fig =plt.figure (figsize = (23,4))


    f = sns.lineplot(data=df, x=df.index, y='Temperature', color="y",
                    alpha=.8, label = 'Temperature')

    ax1.xaxis.set_major_locator(mdates.HourLocator(byhour=None, interval=1, tz=None))
    ax1.xaxis.set_major_formatter(mdates.DateFormatter("%H:%M"))

    #xaxis_ = ax1.xaxis
    #xaxis_.set_major_formatter(DateFormatter('%H:%M:%'))

    ax1.set_ylabel('Temperature')

    labels = ax1.get_xticklabels()
    plt.setp(labels, rotation=45);

ボックスプロットの表示

train_new["match_flag"] = train_new["match"].str[:-3]

fig, ax = plt.subplots(figsize = (20,10)) 
sns.boxplot(x= 'match_flag', y = 'y', data = train_new,sym="")
labels = ax.get_xticklabels() 
plt.setp(labels, rotation=90);

yyプロットの表示

# yyplot 作成関数
def yyplot(y_obs, y_pred):
    yvalues = np.concatenate([y_obs, y_pred])
    ymin, ymax, yrange = np.amin(yvalues), np.amax(yvalues), np.ptp(yvalues)
    fig = plt.figure(figsize=(8, 8))
    plt.scatter(y_obs, y_pred)
    plt.plot([ymin - yrange * 0.01, ymax + yrange * 0.01], [ymin - yrange * 0.01, ymax + yrange * 0.01])
    plt.xlim(ymin - yrange * 0.01, ymax + yrange * 0.01)
    plt.ylim(ymin - yrange * 0.01, ymax + yrange * 0.01)
    plt.xlabel('y_observed', fontsize=24)
    plt.ylabel('y_predicted', fontsize=24)
    plt.title('Observed-Predicted Plot', fontsize=24)
    plt.tick_params(labelsize=16)
    plt.show()

    return fig

Foliumによる地図上の可視化

import folium

def visualize_locations(df,  zoom=10):

    # 図の大きさを指定する。
    f = folium.Figure(width=1000, height=500)

    # 初期表示の中心の座標を指定して地図を作成する。
    center_lat=38.9
    center_lon=-77
    m = folium.Map([center_lat,center_lon], zoom_start=zoom).add_to(f)

    # データフレームの全ての行のマーカーを作成する。
    for i in range(0,len(df)):
        folium.Marker(location=[df["LATITUDE_GROUP"][i],df["LONGITUDE_GROUP"][i]]).add_to(m)
    #for i in range(0,len(df)):
        #folium.Marker(location=[df["LATITUDE_GROUP"][i],df["LONGITUDE_GROUP"][i]],
                      #icon=folium.Icon(color="orange", icon="info-sign")).add_to(m)

    return m

visualize_locations(temp_df_fol)
Back to top