# -*- coding: utf-8 -*-
"""
Created on Sun Oct  6 13:19:06 2019

@author: khh
"""

###############################################################################
print('#################### plottong ##################################')
###############################################################################
import matplotlib.pyplot as plt
# plt.rcParams["font.family"] = "Times New Roman"

params = {
        'font.family': 'Times New Roman',
        'axes.labelsize': 8,
        'text.fontsize': 8,
        'legend.fontsize': 10,
        'xtick.labelsize': 7, #8
        'ytick.labelsize': 9,
        'text.usetex': False,
        'figure.figsize': [7, 4] # instead of 4.5, 4.5
   }
plt.rcParams.update(params)

### descriptive statistics
#
X.describe()

### num_dpi = 300, 600
def export_plot (plot_name, num_dpi):
    plt.savefig('Fig_' +  plot_name + '_plot1.png', dpi = num_dpi, bbox_inches='tight',  pad_inches = 0.01)
    plt.savefig('Fig_' + plot_name + '_plot1.tiff', dpi = num_dpi, bbox_inches='tight',  pad_inches = 0.01, format="tiff", pil_kwargs={"compression": "tiff_lzw"})

# =============================================================================
# ### save plots
# plt.savefig('SHOPA_' +  area_type2 + '_plot1.png', dpi=600, bbox_inches='tight',  pad_inches = 0.01)
# plt.savefig('SHOPA_' + area_type2 + '_plot1.tiff', dpi=600, bbox_inches='tight',  pad_inches = 0.01, format="tiff", pil_kwargs={"compression": "tiff_lzw"})
#     
# =============================================================================
    
    
### plot histo
plt.figure();
X.plot.hist(alpha = 0.5)
plt.show()
export_plot('testplot' , 600)


plt.show()

# X.diff().hist(color='k', alpha=0.5, bins=50)
# plt.show()


# =============================================================================
# # Plot the raw time series
# fig = plt.figure(constrained_layout=True)
# gs = gridspec.GridSpec(2, 3, figure=fig)
# ax = fig.add_subplot(gs[0, :])
# ax.plot(t, y)
# ax.set_xlabel('time [s]')
# ax.set_ylabel('signal')
# 
# =============================================================================

### Good
plt.figure()
# fig, (ax0, ax1) = plt.subplots(ncols=2, constrained_layout=True)
fig, ax1 = plt.subplots(ncols=1, constrained_layout=True)
X.plot.box()
fig = X.plot(subplots=True, figsize=(6, 6));
fig.X.subplot()


### Stacking subplots in two directions
### When stacking in two directions, the returned axs is a 2D numpy array.
#
# If you have to set parameters for each subplot it's handy to iterate over all subplots in a 2D grid using for ax in axs.flat:.
#
### 'q_hosheal2_MEAN', 'q_khos2_MEAN', 'q_dhos3_MEAN'
fig, axs = plt.subplots(2, 2)
axs[0, 0].plot(X['q_hos1_MEAN'], bins = 10)
axs[0, 0].set_title('Axis [0,0]')
axs[0, 1].plot(X['q_hosheal2_MEAN'], bins = 10) #, 'tab:orange')
axs[0, 1].set_title('Axis [0,1]')
axs[1, 0].plot(X['q_khos2_MEAN'], bins =10 )#, 'tab:green')
axs[1, 0].set_title('Axis [1,0]')
axs[1, 1].plot(X['q_dhos3_MEAN'], bins = 10)#, 'tab:red')
axs[1, 1].set_title('Axis [1,1]')

for ax in axs.flat:
    ax.set(xlabel='x-label', ylabel='y-label')

# Hide x labels and tick labels for top plots and y ticks for right plots.
for ax in axs.flat:
    ax.label_outer()
    
### bin must
import matplotlib.pyplot as plt

plt.subplot(2, 1, 1)
plt.plot(X['q_hos1_MEAN'], y, '-', linewidth = 0.1) # 'o-')
plt.title('A tale of 2 subplots')
plt.ylabel('Damped oscillation')

plt.subplot(2, 1, 2)
plt.plot(X['q_hosheal2_MEAN'], y, '.-', linewidth = 0.2)
plt.xlabel('time (s)')
plt.ylabel('Undamped')

plt.show()
export_plot('testplot' , 600)

### Good fig
plt.figure();
X.plot.hist(stacked=True, bins=20)

### hist bin must
import matplotlib.pyplot as plt

plt.figure(figsize = [6.4, 4.8], dpi  = 600); # [6.4, 4.8/9.0], dpi  = 600);

plt.subplot(4, 1, 1)
plt.hist(X['q_hos1_MEAN'], bins= 10) #, linewidth = 0.1)
plt.title('Histogram plot: hos1')
plt.xlabel('Distance(meters)')
plt.ylabel('Freq.')

plt.subplot(4, 1, 2)
plt.hist(X['q_hosheal2_MEAN'], bins = 10) #, linewidth = 0.2)
plt.title('Histogram plot: hosheal2')
plt.xlabel('Distance(meters)')
plt.ylabel('Freq.')

plt.subplot(4, 1, 3)
plt.hist(X['q_khos2_MEAN'], bins = 10) #, linewidth = 0.2)
plt.title('Histogram plot: khos2')
plt.xlabel('Distance(meters)')
plt.ylabel('Freq.')

plt.subplot(4, 1, 4)
plt.hist(X['q_dhos3_MEAN'], bins = 10) #, linewidth = 0.2)
plt.title('Histogram plot: dhos3')
plt.xlabel('Distance(meters)')
plt.ylabel('Freq.')

# plt.tight_layout()

export_plot('Xvars_histogram_plot4' , 600)
plt.show()

####  Good: 
plt.figure(figsize = [6.4, 4.8], dpi  = 600); # [6.4, 4.8/9.0], dpi  = 600);

plt.subplot(1, 1, 1)
plt.hist(X['q_hos1_MEAN'], bins= 10) #, linewidth = 0.1)
plt.title('Histogram plot: hos1')
plt.xlabel('Distance(meters)')
plt.ylabel('Freq.')

plt.tight_layout()
export_plot('Xvars_histogram_plot4=q_hos1' , 600)
plt.show()

plt.subplot(1, 1, 1)
plt.hist(X['q_hosheal2_MEAN'], bins = 10) #, linewidth = 0.2)
plt.title('Histogram plot: hosheal2')
plt.xlabel('Distance(meters)')
plt.ylabel('Freq.')

plt.tight_layout()
export_plot('Xvars_histogram_plot4=q_hosheal2' , 600)
plt.show()

plt.subplot(1, 1, 1)
plt.hist(X['q_khos2_MEAN'], bins = 10) #, linewidth = 0.2)
plt.title('Histogram plot: khos2')
plt.xlabel('Distance(meters)')
plt.ylabel('Freq.')


plt.tight_layout()
export_plot('Xvars_histogram_plot4=q_khos2' , 600)
plt.show()

plt.subplot(1, 1, 1)
plt.hist(X['q_dhos3_MEAN'], bins = 10) #, linewidth = 0.2)
plt.title('Histogram plot: dhos3')
plt.xlabel('Distance(meters)')
plt.ylabel('Freq.')

plt.tight_layout()
export_plot('Xvars_histogram_plot4=q_dhos3' , 600)
plt.show()

plt.figure(figsize = [6.4, 4.8], dpi  = 600); # [6.4, 4.8/9.0], dpi  = 600);

plt.subplot(1, 1, 1)
plt.hist(y, bins= 10) #, linewidth = 0.1)
plt.title('Histogram plot: y(B7_2)')
plt.xlabel('Facility satisfaction')
plt.ylabel('Freq.')

plt.tight_layout()
export_plot('Yvars_histogram_plot4=y(B7_2)' , 600)
plt.show()

###
plt.figure(figsize = [6.4, 4.8], dpi  = 600); # [6.4, 4.8/9.0], dpi  = 600);

# df.columns.tolist()
factor1 = df[['q_hos3_MEAN', 'q2_clc2_MEAN','q_hos2_MEAN','q2_clc3_MEAN','q2_clc32_MEAN','q_dhos2_MEAN','q_hos0_MEAN', 'q_drug3_MEAN']]

corr = factor1.corr()
import seaborn as sns
ax = sns.heatmap(
        corr, 
        vmin=-1, vmax=1, center=0,
        cmap=sns.diverging_palette(20, 220, n=200),
        square=True
)
ax.set_xticklabels(
        ax.get_xticklabels(),
        rotation=45,
        horizontalalignment='right'
);
export_plot('geoqol2016_corrplot1=factor1' , 600)
plt.show()

### corrplot for factors_all
factors_all = df[['q_hos3_MEAN','q_hosheal2_MEAN','q2_clc2_MEAN','q_hos2_MEAN',
                  'q2_clc3_MEAN','q2_clc32_MEAN','q_dhos2_MEAN','q_hos0_MEAN',
                  'q_khos2_MEAN','q_dhos3_MEAN','q_birth_MEAN','q2_clc1_MEAN',
                  'q_hos1_MEAN','q_drug3_MEAN']]
corr = factors_all.corr()
import seaborn as sns
ax = sns.heatmap(
        corr, 
        vmin=-1, vmax=1, center=0,
        cmap=sns.diverging_palette(220, 20, sep=20, as_cmap=True), #(20, 220, n=200), # 220, 20, sep=20, as_cmap=True)
        square=True
)
ax.set_xticklabels(
        ax.get_xticklabels(),
        rotation=45,
        horizontalalignment='right'
);
export_plot('geoqol2016_corrplot1=factors_all' , 600)
plt.show()

###
plt.hist(corr)

labels= list(factors_all)
plt.legend(labels)
# plt.legend(prop={'size': 8})
# plt.plot(corr. corr)
export_plot('geoqol2016_corrplot_2=factors_all' , 600)
plt.show()

###
plt.subplot(1, 1, 1)
plt.plot(factor1, linewidth = 0.1)
plt.title('Histogram plot: hos1')
plt.xlabel('Distance(meters)')
plt.ylabel('Freq.')

plt.tight_layout()
export_plot('Xvars_histogram_plot4=q_dhos3' , 600)
plt.show()





### Good fig
plt.figure();
X.plot.hist(stacked=True, bins=20)

plt.figure();
plt.hist(X['q_hos1_MEAN'], bins= 10, linewidth = 0.1) # 'o-')
plt.show()

### Hexagonal bin plot
#
# X.plot.hexbin(x= 'q_hos1_MEAN', y= y, gridsize=25)

###
from pandas.plotting import andrews_curves
plt.figure()
# andrews_curves(X, 'q_hos1_MEAN') # (data, 'Name')
plt.show()
# shap.summary_plot(shap_values, final_model_features)
# plt.savefig('shap.force_plot1.png')

###
from pandas.plotting import radviz
#
radviz(X, 'q_hos1_MEAN')
plt.show()

### subplots 
#
X.columns.tolist()
# df[['q_hos1_MEAN', 'q_hosheal2_MEAN', 'q_khos2_MEAN', 'q_dhos3_MEAN']].plot(subplots=True, figsize=(6, 6), linewidth=0.5, linestyle='-', color='#006BB2') 
X.plot(subplots=True, figsize=(6, 6), linewidth=0.5, linestyle='-', color='#006BB2') # linewidth=2, linestyle='--', color='#006BB2')
# plt.show()
export_plot('???', 600)
plt.show()
#
plt.figure()
X.plot(subplots=True, layout=(2, 2), figsize=(6, 6), linewidth=0.5, sharex=False);
# plt.show()
export_plot('???', 600)
plt.show()

### imporing DPI in folders
from PIL import Image
import glob
import os

DPI = 600

cwd = os.getcwd()
cwd = 'C://0.DATA/_pywork/data_ML/geoqol2016/ML_qol_models/geoqol2016_2019-10-03_VIFunchecked_FAn=4confirmed/dpi600'
os.chdir(cwd)
list_img = glob.glob('*') #('*.png') ###("*")

for img in list_img:
    im = Image.open(img) 
    im.save(img, dpi=(DPI,DPI))
    print(img)
    

