0
0

More than 1 year has passed since last update.

CSVファイルから散布図とグラフを作成し,1枚の図で表示する方法(2軸グラフ)

Last updated at Posted at 2023-03-28

プログラムについて

ChatGPTを使って,CSVファイルから散布図とグラフを作成し,1枚の図で表示するプログラムを作りました.

環境

  • MacBook Air(M1, 2020)
  • Python 3.8.8

プログラム

ScatterPlot3.py
import sys
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

# コマンドライン引数からファイル名を取得する
if len(sys.argv) != 4:
    print("Usage: python graph.py file1.csv file2.csv file3.csv")
    sys.exit(1)

file1 = sys.argv[1]
file2 = sys.argv[2]
file3 = sys.argv[3]

# 1つ目のCSVファイルを読み取る
df1 = pd.read_csv(file1)
cols1 = df1.columns.tolist()
x_col1 = cols1[0]  # 1つ目の列をxとする
y_col1 = cols1[1]  # 2つ目の列をyとする
x1 = df1[x_col1]
y1 = df1[y_col1]

# 2つ目のCSVファイルを読み取る
df2 = pd.read_csv(file2)
cols2 = df2.columns.tolist()
x_col2 = cols2[0]  # 1つ目の列をxとする
y_col2 = cols2[1]  # 2つ目の列をyとする
x2 = df2[x_col2]
y2 = df2[y_col2]

# 3つ目のCSVファイルを読み取る
df3 = pd.read_csv(file3)
cols3 = df3.columns.tolist()
x_col3 = cols3[0]  # 1つ目の列をxとする
y_col3_1 = cols3[1]  # 2つ目の列をy1とする
y_col3_2 = cols3[2]  # 3つ目の列をy2とする
x3 = df3[x_col3]
y3_1 = df3[y_col3_1]
y3_2 = df3[y_col3_2]

# グラフを作成する
fig, ax1 = plt.subplots()

# 1つ目のデータをプロットする
color = 'tab:red'
ax1.set_xlabel('time')
ax1.set_ylabel('$log_{10}(r)$', color='black')
ax1.scatter(x1, np.log10(y1), color=color, label='1', s=6)

# 2つ目のデータをプロットする
color = 'tab:blue'
ax1.scatter(x1, np.log10(y2), color=color, label='2', s=6)

# 3つ目のデータをプロットする
ax2 = ax1.twinx()
color = 'tab:green'
ax2.set_ylabel('sine', color='black')
ax2.plot(x3, y3_1, color='black', label='Input')
ax2.plot(x3, y3_2, color='green', label='Output')

# グラフの凡例を表示する
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines1 + lines2, labels1 + labels2, loc='best')

# グラフの設定を調整する
fig.tight_layout()

# PNG形式で保存する
plt.savefig('graph.png')

実行結果

今回はテストとして,大きさの異なる2つのデータ(test1.csv, test2.csv),
sin関数のデータ(test3.csv)の合計3つのデータを表示するようにしています.

実行例
python3 ScatterPlot3.py test1.csv test2.csv test3.csv

作成された図は以下のようになっています.

graph.png

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