import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans, AgglomerativeClustering, AffinityPropagation, DBSCAN
external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']
app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
#データの読み込み
dfA = pd.read_csv("C:/Users/motch/Documents/SMTAM/py_bubble.csv")
dfA['系列'] = dfA['系列'].astype(str)
dfA['X'] = pd.to_datetime(dfA['X'])
#◆◆◆グラフ1◆◆◆
fig = px.scatter(dfA, x="X", y="Y",
size="Z", color="系列",
log_x=True)
fig.update_layout(
xaxis = dict(
type = 'date',
tickformat = '%H:%M'
)
)
#◆◆◆グラフ2◆◆◆
dfB = dfA.iloc[:,1:3].values
#Within -cluster sum of squares(WCSS)= 「各クラスターの重心とそのクラスターに割り付けられたデータとの距離の総和」
#「最初のシードとなるデータの点の選び方」を適当にばらまくのではなくて、
#さらに良い置き方があるのではないかということで考案されたのが K-means++(プラスプラス)法というアルゴリズム
wcss = []
for i in range(1, 10):
kmeans = KMeans(n_clusters = i, init = "k-means++", max_iter = 500, n_init = 10, random_state = 123)
kmeans.fit(dfB)
wcss.append(kmeans.inertia_)
fig2 = go.Figure(data = go.Scatter(x = [1,2,3,4,5,6,7,8,9,10], y = wcss))
fig2.update_layout(title='WCSS vs. Cluster number',
xaxis_title='Clusters',
yaxis_title='WCSS')
#◆◆◆グラフ3◆◆◆
kmeans = KMeans(n_clusters = 3, init="k-means++", max_iter = 500, n_init = 10, random_state = 0)
identified_clusters = kmeans.fit_predict(dfB)
data_with_clusters = dfA.copy()
data_with_clusters['Cluster'] = identified_clusters
data_with_clusters['Cluster'] = data_with_clusters['Cluster'].astype(str)
fig3 = px.scatter(data_with_clusters, x = 'X', y='Y',
size='Z', color='Cluster', log_x=True)
fig3.update_layout(
xaxis = dict(
type = 'date',
tickformat = '%H:%M'
)
)
fig.show()
app.layout = html.Div(children=[
html.H1(children='Hello Dash'),
html.Div(children='''
Dash: A web application framework for Python.
'''),
dcc.Graph(
id='example-graph',
figure=fig
),
dcc.Graph(
id='example-graph2',
figure=fig2
),
dcc.Graph(
id='example-graph3',
figure=fig3
)
])
if __name__ == '__main__':
app.run_server(debug=True, use_reloader=False)
この記事が気に入ったらサポートをしてみませんか?