0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Streamlitでアプリ作成① ~ChatGPTでのデータ可視化の簡易実装~

Posted at

はじめに

仕事で簡単な分析をする際に、いちいちコード書いて分析するのが面倒なので、Streamlitというライブラリを用いて少しずつアプリ開発をしていこうと思う。

実装した機能

今回はStreamlitでどのようなことができるのかを知りたかったので、ChatGPTに「アンケートデータを簡単に可視化できるようなアプリを作って」という依頼をし、出てきたコードをそのまま実行した。
コード内で実装した機能は以下である。
①csvデータのアップロード
image.png
②データのプレビュー
image.png
③グラフ(ヒストグラム/棒グラフ/折れ線グラフ)
image.png
④散布図
image.png
⑤ヒートマップ
image.png

実装したコード

import streamlit as st
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

st.title("データ可視化")

uploaded_file = st.file_uploader("CSVファイルをアップロードしてください", type="csv")

if uploaded_file:
    df = pd.read_csv(uploaded_file)

    st.subheader("データのプレビュー")
    st.dataframe(df)

    # 数値型カラムだけ抽出
    numeric_cols = df.select_dtypes(include='number').columns.tolist()

    st.subheader("グラフ")
    col1 = st.selectbox("カラムの選択", numeric_cols)
    chart_type = st.radio("グラフの種類", ['ヒストグラム', '棒グラフ', '折れ線グラフ'])

    if chart_type == 'ヒストグラム':
        fig1 = sns.histplot(df[col1], kde=True).figure
        st.pyplot(fig1)
    elif chart_type == '棒グラフ':
        fig2 = sns.countplot(x=col1, data=df).figure
        st.pyplot(fig2)
    elif chart_type == '折れ線グラフ':
        st.line_chart(df[col1])

    st.subheader("散布図")
    x_var = st.selectbox("X軸を選択", numeric_cols, key="x_var")
    y_var = st.selectbox("Y軸を選択", numeric_cols, key="y_var")

    if x_var and y_var:
        fig3, ax3 = plt.subplots()
        sns.scatterplot(x=df[x_var], y=df[y_var], hue=df.get("性別"), ax=ax3)
        st.pyplot(fig3)

    st.subheader("ヒートマップ")
    corr = df[numeric_cols].corr()
    fig4, ax4 = plt.subplots()
    sns.heatmap(corr, annot=True, cmap="coolwarm", ax=ax4)
    st.pyplot(fig4)

else:
    st.info("まずはCSVファイルをアップロードしてください。")

感想

Streamlitへの分析結果の渡し方は理解しないといけなさそうだが、簡単にwebアプリが実装できると分かってよかった。データ可視化はデータビジュアライゼーションに関する本なども参考にしながら、アップデートしていこうと思う。次回は、ビジュアライゼーションについて書くと思う。(多分)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?