ちょいめも

物理/Python/Cの雑記帳

PC

・OS
Microsoft Windows 10 Home 64bit 日本語 DSP
13,480
http://kakaku.com/item/K0001027613/

・モニタ IODATA KH2750V-UHD [27インチ ブラック]
39,743
http://kakaku.com/item/K0001080719/

マザボ asus PRIME B360-PLUS
11,138
http://kakaku.com/item/K0001044810/

・CPU
intel core i7 8700
35,883
http://kakaku.com/item/K0001002086/

・メモリ
Corsair CMK16GX4M2A2666C16 [DDR4 PC4-21300 8GB 2枚組]
19,262
http://kakaku.com/item/K0000799289/

ビデオカード
asus PH-GTX1050TI-4G [PCIExp 4GB]
18,798
http://kakaku.com/item/K0000920443/

SSD
サムスン 860 EVO MZ-76E250B/IT
7,980
http://kakaku.com/item/K0001027991/

・電源
ENERMAX Revolution DUO ERD500AWL-F
7030
http://kakaku.com/item/K0000931692/

・BDドライブ
イオニア BDR-211JBK [ブラック]
13,006
http://kakaku.com/item/K0000970025/

python+tkinterでグラフ表示 classで書き直し

import os
import re
import numpy as np
import pandas as pd
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.filedialog as tkdialog
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

NUM_FILE = 3
NUM_GRAPH = 5

graph_pos = [1,2,3,5,6] #グラフの位置
x_name='x'
y_name=['a','b','c','d','e'] #グラフの数に対応 csvの列名
def_data_name = 'no data' #凡例 デフォルト


class Application(tk.Frame):

	def __init__(self, master=None):

		self.label = [0 for i in range(NUM_FILE)]
		self.chk_var = [0 for i in range(NUM_FILE)]
		self.chk_box = [0 for i in range(NUM_FILE)]
		self.edit_box = [0 for i in range(NUM_FILE)]
		self.fopen_button = [0 for i in range(NUM_FILE)]

		self.graph = [[0 for i in range(NUM_FILE)] for j in range(NUM_GRAPH)]
		self.data = [0 for i in range(NUM_FILE)]
		self.ax = [0 for i in range(NUM_GRAPH)]

		self.filename = [0 for i in range(NUM_FILE)]
		self.xname = [0 for i in range(NUM_GRAPH)]
		self.max_index = [[0 for i in range(NUM_GRAPH)] for j in range(NUM_FILE)]
		self.max_value = [[0 for i in range(NUM_GRAPH)] for j in range(NUM_FILE)]


		super().__init__(master)
		self.pack()
		self.input_file_label(0, 1)
		self.input_file_entry(1, 0)
		self.setting_x_axis(0, 4)
		self.save_figure_button(1, 7)
		self.save_value_button(2, 7)
		self.sub_win_button(0, 8)

		#グラフ
		plt.style.use('ggplot')
		fig = plt.Figure(figsize=(12, 5))#, dpi=100) #(col,row)
		#tkinterに追加するcanvasにfigを追加する
		self.canvas = FigureCanvasTkAgg(fig, master)
		self.canvas.get_tk_widget().pack()

		#グラフ (行、列、場所)
		for i in range(NUM_GRAPH):
			self.ax[i] = fig.add_subplot(2, 3, graph_pos[i])
			for j in range(NUM_FILE):
				self.graph[i][j], = self.ax[i].plot([], [], label=def_data_name)
			self.ax[i].legend()

		fig.tight_layout()

		self.frame_out = tk.Frame()
		self.test_edit_box()
		self.frame_out.pack(side=tk.LEFT, padx=0)


	#グラフ描画
	def draw(self):
		#軸範囲
		y_min = 0
		y_max = 150
		x_min = 0
		x_max = 0

		for i in range(NUM_FILE):
			#チェックボックスにチェックが入っている時
			if self.chk_var[i].get():
				self.data[i] = pd.read_csv(self.edit_box[i].get())
				self.filename[i], ext = os.path.splitext(os.path.basename(self.edit_box[i].get()))


				for j in range(NUM_GRAPH):
					x = self.data[i][x_name].values
					y = self.data[i][y_name[j]].values
					self.graph[j][i].set_data(x, y)

					#軸設定 軸範囲手動
					if self.auto_scale_chk_box_var.get():
						if len(self.x_axis_min_edit_box.get()) > 0 and len(self.x_axis_max_edit_box.get()) > 0 and float(self.x_axis_max_edit_box.get()) - float(self.x_axis_min_edit_box.get()) > 0:
							self.ax[j].set_xlim(float(self.x_axis_min_edit_box.get()), float(self.x_axis_max_edit_box.get()))
					#軸範囲 自動設定
					else:
						x_max = x.max() if x.max() > x_max else x_max
						x_min = x.min() if x.min() < x_min else x_min
						self.ax[j].set_xlim(x_min, x_max)
					self.ax[j].set_ylim(y_min, y_max)

					self.graph[j][i].set_label('File%d %s' % (i+1, y_name[j]))
					self.ax[j].legend()

					#値出力用に格納 [file][graph] 最初にファイルをもってくることでファイルの次元を指定してグラフの値を全て書きだせるようにする
					self.xname[j] = y_name[j]
					self.max_index[i][j] = y.argmax()
					self.max_value[i][j] = y.max()

			else:
				for j in range(NUM_GRAPH):
					self.graph[j][i].set_data([], [])
					self.graph[j][i].set_label(def_data_name)
					self.ax[j].legend()


	def save_value_button(self, r, c):
		self.savevalue_button = tk.Button(self, text='Save Value', width=10)
		self.savevalue_button.bind("<ButtonRelease-1>", self.save_value) #左ボタンを押してそのボタンを放した時に発生
		self.savevalue_button.grid(row=r, column=c, padx=1, pady=1)


	def save_value(self, event):
		self.draw()

		#default file name取得
		val_name = ''
		for i in range(NUM_FILE):
			if self.chk_var[i].get():
				val_name = val_name + '_' + self.filename[i]

		value_data = self.xname
		col_name1 = 'filename'
		col_name2 = 'pos'
		for i in range(NUM_FILE):
			if self.chk_var[i].get():
				col_name1 = np.vstack([col_name1, self.filename[i], self.filename[i]])
				col_name2 = np.vstack([col_name2, 'peak_index', 'peak_value'])
				value_data = np.vstack([value_data, self.max_index[i], self.max_value[i]])

		#列名挿入
		value_data = np.hstack([col_name1, col_name2, value_data])

		save_value_name = tkdialog.asksaveasfilename(filetypes=[('data files','*.csv')], initialdir=os.getcwd(), initialfile=val_name)
		np.savetxt(save_value_name + '.csv', value_data.T, fmt='%s', delimiter = ',')


	def input_file_label(self, r, c):
		#グラフファイル入力 ラベル
		self.chk_box_label = tk.Label(self, text='Graph ON/OFF')
		self.chk_box_label.grid(row=r, column=c, padx=1, pady=1, sticky=tk.W)

		self.edit_box_label = tk.Label(self, text='File Path')
		self.edit_box_label.grid(row=r, column=c+1, padx=10, pady=1, sticky=tk.W)


	def input_file_entry(self, r, c):
		for i in range(NUM_FILE):
			self.label[i] = tk.Label(self, text='File%d' % (i+1))
			self.label[i].grid(row=i+r, column=c, padx=10, pady=1)
			#チェックボックス
			self.chk_var[i] = tk.IntVar()
			self.chk_box[i] = tk.Checkbutton(self, variable=self.chk_var[i], command=self.update)
			self.chk_box[i].grid(row=i+r, column=c+1, padx=1, pady=1)
			#入力ボックス
			self.edit_box[i] = tk.Entry(self, width=60)
			self.edit_box[i].insert(tk.END,'input file path (full path)')
			self.edit_box[i].grid(row=i+r, column=c+2, padx=10, pady=1)

			#ファイルダイアログ
			self.fopen_button[i] = tk.Button(self, text='File%d open' % (i+1), width=10)
			self.fopen_button[i].bind("<ButtonRelease-1>", self.file_dialog) #左ボタンを押してそのボタンを放した時に発生
			self.fopen_button[i].grid(row=i+r, column=c+3, padx=1, pady=1)


	def file_dialog(self, event):
		fname = tkdialog.askopenfilename(filetypes=[('data files','*.csv')], initialdir=os.getcwd())
		#ボタンの名前から番号を取り出す(文字列から数値を取り出す)
		index = int(re.sub(r'\D', '', event.widget["text"]))-1
		#入力ボックスの文字を消す
		self.edit_box[index].delete(0, tk.END)
		self.edit_box[index].insert(tk.END, fname)


	def save_figure_button(self, r, c):
		self.save_button = tk.Button(self, text='Save Figure', width=10)
		self.save_button.bind("<ButtonRelease-1>", self.save_figure) #左ボタンを押してそのボタンを放した時に発生
		self.save_button.grid(row=r, column=c, padx=1, pady=1)


	def save_figure(self, event):
		#default file name取得
		fig_name = ''
		for i in range(NUM_FILE):
			if self.chk_var[i].get():
				fig_name = fig_name + '_' + self.filename[i]

		save_figure_name = tkdialog.asksaveasfilename(filetypes=[('data files','*.png')], initialdir=os.getcwd(), initialfile=fig_name)
		self.draw()
		self.canvas.draw()
		self.canvas.print_figure(save_figure_name, dpi=300)


	def setting_x_axis(self, r, c):

		#グラフ設定
		auto_scale_chk_box_label = tk.Label(self, text='auto scale ON/OFF')
		auto_scale_chk_box_label.grid(row=r, column=c, padx=1, pady=1, sticky=tk.W)

		self.auto_scale_chk_box_var = tk.IntVar()
		auto_scale_chk_box = tk.Checkbutton(self, variable=self.auto_scale_chk_box_var, command=self.change_axis_range)
		auto_scale_chk_box.grid(row=r+1, column=c, padx=1, pady=1)

		x_axis_min_label = tk.Label(self, text='x axis min')
		x_axis_min_label.grid(row=r, column=c+1, padx=1, pady=1, sticky=tk.W)
		self.x_axis_min_edit_box = tk.Entry(self, width=10)
		self.x_axis_min_edit_box.grid(row=r+1, column=c+1, padx=1, pady=1)

		x_axis_max_label = tk.Label(self, text='x axis max')
		x_axis_max_label.grid(row=r, column=c+2, padx=1, pady=1, sticky=tk.W)
		self.x_axis_max_edit_box = tk.Entry(self, width=10)
		self.x_axis_max_edit_box.grid(row=r+1, column=c+2, padx=1, pady=1)


	#グラフx軸変更
	def change_axis_range(self):
		if self.auto_scale_chk_box_var.get():
			for i in range(NUM_GRAPH):
				if len(self.x_axis_min_edit_box.get()) > 0 and len(self.x_axis_max_edit_box.get()) > 0 and float(self.x_axis_max_edit_box.get()) - float(self.x_axis_min_edit_box.get()) > 0:
					self.ax[i].set_xlim(float(self.x_axis_min_edit_box.get()), float(self.x_axis_max_edit_box.get()))
		else:
			self.draw()

		self.canvas.draw()


	#設定ウインドウ呼び出しボタン 別ウインドウが開く
	def sub_win_button(self, r, c):
		sub_win_button = tk.Button(self, text='Sub Window', width=10)
		sub_win_button.bind("<ButtonRelease-1>", self.sub_win_event) #左ボタンを押してそのボタンを放した時に発生
		sub_win_button.grid(row=r, column=c, padx=1, pady=1)


	def sub_win_event(self, event):
		sub_win = tk.Toplevel()
		sub_win.title("Setting")
		sub_win.geometry('300x200')

		self.sub_win_edit_box = tk.Entry(sub_win, width=10)
		try:
			self.sub_win_edit_box.insert(tk.END, self.save_sub_win_value)
		except:
			self.sub_win_edit_box.insert(tk.END, 0)
		self.sub_win_edit_box.grid(row=0, column=0, padx=1, pady=1)

		save_button = tk.Button(sub_win, text="Save Value", width=10)
		save_button.bind("<ButtonRelease-1>", self.sub_win_out) #左ボタンを押してそのボタンを放した時に発生
		save_button.grid(row=1, column=0, padx=1, pady=1)

		close_button = tk.Button(sub_win, text="CLOSE", width=10, command=sub_win.destroy)
		close_button.grid(row=2, column=0, padx=1, pady=1)


	#サブウインドウの値を保存
	def sub_win_out(self, event):
		self.save_sub_win_value = self.sub_win_edit_box.get()


	def update(self):
		self.draw()
		self.canvas.draw()

		#self.test_edit_box()でテキストボックスが生成されるので、destroyで削除する
		self.edit_box_out.destroy()
		self.test_edit_box()

		try:
			print(self.save_sub_win_value)
		except:
			print('no data')

	def test_edit_box(self):

		name=['a', 'b', 'c', 'd', 'e', 'f']

		for i in range(NUM_FILE):
			label1 = tk.Label(self.frame_out, text='File{}'.format(i+1))
			label1.grid(row=0, column=i+1, padx=2, pady=0)

		for i in range(len(name)):
			label2 = tk.Label(self.frame_out, text='{}'.format(name[i]))
			label2.grid(row=i+1, column=0, padx=2, pady=0)

		for j in range(len(name)):
			for i in range(NUM_FILE):
				self.edit_box_out = tk.Entry(self.frame_out, width=8)
				if self.chk_var[i].get():
					self.edit_box_out.insert(tk.END, '{:.3f}'.format(self.max_value[i][0])) #一個目のグラフ #[file][graph]
				else:
					self.edit_box_out.insert(tk.END, 0) #一個目のグラフ #[file][graph]
				self.edit_box_out.configure(state='readonly')
				self.edit_box_out.grid(row=j+1, column=i+1, padx=2, pady=0)


if __name__ == '__main__':
	root = tk.Tk()
#	root.resizable(0,0) #ウィンドウのサイズ固定
	root.title('Title1')
	root.geometry('1300x720')
	root.iconbitmap('icon.ico')
	app = Application(master=root)
	app.mainloop()
ret = [data[i*4+4:i*4+4+4].mean() for i in range(5)]
#1-3
ret2 = [data[i*4+4]-data[i*4+6] for i in range(5)]
#4-2
ret3 = [data[i*4+7]-data[i*4+5] for i in range(5)]
import os
import numpy as np
import tkinter as tk
import tkinter.messagebox as tkmsg

VER = 1.00
app_dir = 'D:\\python\\Anaconda3\\PythonScript\\app'

latest_version = np.array(os.listdir(app_dir)).astype(float).max()
root = tk.Tk()
if latest_version > VER:
	ret = tkmsg.askokcancel('INFO', 'The latest ver is available\nVer.{:.2f} → Ver.{:.2f}\nOK:Open the folder'.format(VER, latest_version))
	if ret == True:
		os.popen('explorer {}'.format(app_dir))
root.mainloop()

Python + Tkinterでグラフ表示

import os
import re
import numpy as np
import pandas as pd
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.filedialog as tkdialog
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg

#----- 定義 & グローバル変数 -----
NUM_FILE = 3
NUM_GRAPH = 5

label = [0 for i in range(NUM_FILE)]
chk_var = [0 for i in range(NUM_FILE)]
chk_box = [0 for i in range(NUM_FILE)]
edit_box = [0 for i in range(NUM_FILE)]
graph = [[0 for i in range(NUM_FILE)] for j in range(NUM_GRAPH)]
data = [0 for i in range(NUM_FILE)]
ax = [0 for i in range(NUM_GRAPH)]

#グラフ
plt.style.use('ggplot')
fig = plt.Figure(figsize=(12, 6))#, dpi=100) #(col,row)
#↓この書き方はグラフだけ個別に開いてしまう、なぜかは不明
#fig, axes = plt.subplots(nrows = 2, ncols = 2, figsize=(5, 5), sharex = False)

x_name='x'
y_name=['a','b','c','d','e'] #グラフの数に対応 csvの列名
def_data_name = 'no data' #凡例 デフォルト

#グラフ描画
def draw():

	#軸範囲
	y_min = 0
	y_max = 150
	x_min = [0 for i in range(NUM_GRAPH)]
	x_max = [0 for i in range(NUM_GRAPH)]

	for i in range(NUM_FILE):
		#チェックボックスにチェックが入っている時
		if chk_var[i].get():
			data[i] = pd.read_csv(edit_box[i].get())

			for j in range(NUM_GRAPH):
				x = data[i][x_name].values
				y = data[i][y_name[j]].values
				graph[j][i].set_data(x, y)

				#軸設定 軸範囲手動
				if auto_scale_chk_box_var.get():
					if len(x_axis_min_edit_box.get()) > 0 and len(x_axis_max_edit_box.get()) > 0 and float(x_axis_max_edit_box.get()) - float(x_axis_min_edit_box.get()) > 0:
						ax[j].set_xlim(float(x_axis_min_edit_box.get()), float(x_axis_max_edit_box.get()))
				#軸範囲 自動設定
				else:
					x_max[j] = x.max() if x.max() > x_max[j] else x_max[j]
					x_min[j] = x.min() if x.min() > x_min[j] else x_min[j]
					ax[j].set_xlim(x_min[j], x_max[j])
				ax[j].set_ylim(y_min, y_max)

				graph[j][i].set_label('File%d %s' % (i+1, y_name[j]))
				ax[j].legend()

		else:
			for j in range(NUM_GRAPH):
				graph[j][i].set_data([], [])
				graph[j][i].set_label(def_data_name)
				ax[j].legend()


def combo1list():
	if rdo_var.get() == 0:
		combo1['values'] = ('2', '4', '6', '8', '10')
	elif rdo_var.get() == 1:
		combo1['values'] = ('5', '10', '15', '20', '25')
	combo1.current(0) #デフォルト値の最初の要素


def combo1_selected(event):
	print('combo1 = %s' % val1.get())


def combo2_selected(event):
	print('combo2 = %s' % val2.get())


def file_dialog(event):
	fname = tkdialog.askopenfilename(filetypes=[('data files','*.csv')], initialdir=os.getcwd())
	#ボタンの名前から番号を取り出す(文字列から数値を取り出す)
	index = int(re.sub(r'\D', '', event.widget["text"]))-1
	#入力ボックスの文字を消す
	edit_box[index].delete(0, tk.END)
	edit_box[index].insert(tk.END, fname)

#グラフ更新
def update():
	draw()
	canvas.draw()


#グラフx軸変更
def change_axis_range():
	if auto_scale_chk_box_var.get():
		for i in range(NUM_GRAPH):
			if len(x_axis_min_edit_box.get()) > 0 and len(x_axis_max_edit_box.get()) > 0 and float(x_axis_max_edit_box.get()) - float(x_axis_min_edit_box.get()) > 0:
				ax[j].set_xlim(float(x_axis_min_edit_box.get()), float(x_axis_max_edit_box.get()))
	draw()
	canvas.draw()


if __name__ == '__main__':

    #----- tk -----
	root = tk.Tk()
	root.title('Title')
	root.geometry('1300x600')

	#グラフファイル入力、設定フレーム
	setting_frame = tk.Frame(root, padx=10, pady=5)
	#グラフ表示フレーム
	graph_frame   = tk.Frame(root, padx=10, pady=5)

	#tkinterに追加するcanvasにfigを追加する
	canvas = FigureCanvasTkAgg(fig, master=graph_frame)
	canvas.get_tk_widget().pack(side=tk.LEFT)


	#グラフファイル入力 ラベル
	chk_box_label = tk.Label(setting_frame, text='Graph ON/OFF')
	chk_box_label.grid(row=0, column=1, padx=1, pady=1, sticky=tk.W)

	edit_box_label = tk.Label(setting_frame, text='File Path')
	edit_box_label.grid(row=0, column=2, padx=1, pady=1, sticky=tk.W)


	#ファイル入力
	for i in range(NUM_FILE):
		#ラベル
		label[i] = tk.Label(setting_frame, text='File %d' % (i+1))
		label[i].grid(row=i+1, column=0, padx=10, pady=1)
		#チェックボックス
		chk_var[i] = tk.IntVar()
		chk_box[i] = tk.Checkbutton(setting_frame, variable=chk_var[i], command=update)
		chk_box[i].grid(row=i+1, column=1, padx=1, pady=1)
		#入力ボックス
		edit_box[i] = tk.Entry(setting_frame, width=100)
#		edit_box[i].insert(tk.END,'ファイルパスを入力してください')
		edit_box[i].insert(tk.END,'D:\\python\\Anaconda3\\PythonScript\\graph_gui\\curveplot_sample%s.csv' % (i+1))
		edit_box[i].grid(row=i+1, column=2, padx=10, pady=1)

		#ファイルダイアログ
		fopen_button = tk.Button(setting_frame, text='File%d open' % (i+1), width=10)
		fopen_button.bind("<ButtonRelease-1>", file_dialog) #左ボタンを押してそのボタンを放した時に発生
		fopen_button.grid(row=i+1, column=3, padx=1, pady=1)


	#グラフ設定
	auto_scale_chk_box_label = tk.Label(setting_frame, text='auto scale ON/OFF')
	auto_scale_chk_box_label.grid(row=0, column=4, padx=10, pady=1, sticky=tk.W)

	auto_scale_chk_box_var = tk.IntVar()
	auto_scale_chk_box = tk.Checkbutton(setting_frame, variable=auto_scale_chk_box_var, command=change_axis_range)
	auto_scale_chk_box.grid(row=1, column=4, padx=1, pady=1)

	x_axis_min_label = tk.Label(setting_frame, text='x axis min')
	x_axis_min_label.grid(row=0, column=5, padx=10, pady=1, sticky=tk.W)
	x_axis_min_edit_box = tk.Entry(setting_frame, width=10)
	x_axis_min_edit_box.grid(row=1, column=5, padx=10, pady=1)

	x_axis_max_label = tk.Label(setting_frame, text='x axis max')
	x_axis_max_label.grid(row=0, column=6, padx=10, pady=1, sticky=tk.W)
	x_axis_max_edit_box = tk.Entry(setting_frame, width=10)
	x_axis_max_edit_box.grid(row=1, column=6, padx=10, pady=1)

	#Combobox1 ドロップダウンリストとラジオボタン テスト配置
	rdo_var = tk.IntVar()
	rdo_var.set(0)
	rdo0 = tk.Radiobutton(setting_frame, text='1', variable=rdo_var, value=0, command=combo1list)
	rdo0.grid(row=2, column=4, padx=1, pady=1)
	rdo1 = tk.Radiobutton(setting_frame, text='2', variable=rdo_var, value=1, command=combo1list)
	rdo1.grid(row=2, column=5, padx=1, pady=1)

	val1 = tk.StringVar()
	combo1 = ttk.Combobox(setting_frame, state='readonly', textvariable=val1)
	combo1.bind('<<ComboboxSelected>>', combo1_selected)
	combo1list()
	combo1.grid(row=3, column=4, padx=1, pady=1)

	#Combobox2 テスト配置
	val2 = tk.StringVar()
	combo2 = ttk.Combobox(setting_frame, state='readonly', textvariable=val2)
	combo2.bind('<<ComboboxSelected>>', combo2_selected)
	combo2['values'] = ('TEST1', 'TEST2', 'TEST3')
	combo2.current(0) #デフォルト値の最初の要素
	combo2.grid(row=4, column=4, padx=1, pady=1)


	#グラフ (行、列、場所)
	graph_pos = [1,2,3,5,6] #グラフの位置
	for i in range(NUM_GRAPH):
		ax[i] = fig.add_subplot(2, 3, graph_pos[i])
		for j in range(NUM_FILE):
			graph[i][j], = ax[i].plot([], [], label=def_data_name)
		ax[i].legend()

	fig.tight_layout()


	setting_frame.pack(anchor=tk.NW) #tk.NW:左上寄せ
	graph_frame.pack(anchor=tk.NW) #tk.NW:左上寄せ

	root.mainloop() #ここまで

batファイルからpythonスクリプトを起動
・RunScript.bat
cd /d %~dp0
D:\python\Anaconda3\python.exe test.py
・RunScript.vbs
Dim oShell
Set oShell = WScript.CreateObject ("WSCript.shell")
oShell.run "D:\python\Anaconda3\PythonScript\graph_gui\RunScript.bat",0
Set oShell = Nothing

3次方程式を解く

import numpy as np

def third_order_eq(a, b, c, d):

	term1 = (((-27*a**2*d + 9*a*b*c - 2*b**3)**2 + 4*(3*a*c - b**2)**3)**(1/2) - 27*a**2*d + 9*a*b*c - 2*b**3)**(1/3)
	term2 = 3*2**(1/3)*a
	term3 = 3*a*c - b**2
	term4 = b/(3*a)
	term5 = -1/(6*2**(1/3)*a)
	term8 = 3*2**(2/3)*a
	term6 = complex(1, -3**(1/2))
	term7 = complex(1, 3**(1/2))
	
	sol1 = term1/term2 - (2**(1/3)*term3)/(3*a*term1) - term4
	sol2 = term5*term6*term1 + (term7*term3)/(term8*term1) - term4
	sol3 = term5*term7*term1 + (term6*term3)/(term8*term1) - term4
	
	return sol1, sol2, sol3
	
if __name__ == '__main__':
	
	#3次方程式 係数
	coeff2 = [123, 456, 789, 101]

	x1, x2, x3 = np.roots(coeff2)
	print(x1)
	print(x2)
	print(x3)
	
	x1, x2, x3 = (third_order_eq(coeff2[0], coeff2[1], coeff2[2], coeff2[3]))
	print(x1)
	print(x2)
	print(x3)
	
	if x1.imag < 1e-10 and x1.imag > -1e-10:
		print('x1 = %.10f' % x1.real)
	if x2.imag < 1e-10 and x2.imag > -1e-10:
		print('x2 = %.10f' % x2.real)
	if x3.imag < 1e-10 and x3.imag > -1e-10:
		print('x3 = %.10f' % x3.real)

pandas、matplotlibでヒストグラム表示

#csv読み込んでヒストグラム表示
#第一引数:csvフルパス

import sys
import os
import matplotlib
import matplotlib.pyplot as plt
import pandas as pd

argvs = sys.argv #引数取得
argc = len(argvs) #引数の個数

if argc != 2:
	print('引数1 : csvファイル フルパス\n')
	input('終了します。何かキーをおしてください。。。\n')
	sys.exit()

dirname, filename = os.path.split(argvs[1])
df = pd.read_csv(argvs[1]) #csv読み込み

#plt.style.use('ggplot') 
#font = {'family' : 'meiryo'}
#matplotlib.rc('font', **font)

#----------グラフ1つ描画----------
df.plot( y=['a', 'e'], bins=10, alpha=0.5, figsize=(5,4), kind='hist') #αは透過 0~1


#----------グラフ複数描画----------
fig, axes = plt.subplots(nrows=2, ncols=3, figsize=(15, 10), sharex = False) #sharexはx軸を共有するかどうか

df.plot(y=['a', 'e'], bins=10, alpha=1.0, kind='hist', stacked=True, ax=axes[0,0]) #stacked:積み上げ
axes[0,0].set_title('ae')
axes[0,0].set_xlabel("X")
ave = df['a'].mean()
axes[0,0].text(ave,7,"ave:%.1f" % ave, color='blue', bbox=dict(facecolor='none', edgecolor='blue', pad=5.0)) #平均の位置にテキストを表示したり

df.plot(y=['b', 'c'], bins=10, alpha=1.0, kind='hist', stacked=True, ax=axes[0,1])
axes[0,1].set_title('bc')
axes[0,1].set_xlabel("X")
ave = df['b'].mean()
axes[0,1].text(0.1,0.5,"ave:%.1f" % ave, transform = axes[0,1].transAxes,
		color='blue', bbox=dict(facecolor='none', edgecolor='blue', pad=5.0)) #textの位置をグラフ軸座標で描画。最大1

df.plot(y=['a', 'b', 'c', 'd', 'e'], bins=10, alpha=1.0, kind='hist', stacked=True, ax=axes[0,2])
axes[0,2].set_title('abcde')
axes[0,2].set_xlabel("X")

df.plot(y=['d'], bins=10, alpha=1.0, kind='hist', stacked=True, ax=axes[1,0])
axes[1,0].set_title('d')
axes[1,0].set_xlabel("X")

df.plot(y=['e'], bins=10, alpha=1.0, kind='hist', stacked=True, ax=axes[1,1])
axes[1,1].set_title('e')
axes[1,1].set_xlabel("X")

axes[1,2].axis('off') #空白

fig.tight_layout()  # タイトルとラベルが被るのを解消

plt.savefig(dirname + '\histogram.png') #複数グラフをcsvと同じ場所に保存


matplotlib覚書

よく忘れるので覚書

import matplotlib.pyplot as plt

#----------折れ線グラフを1つ描画----------
x = [1,2,3,4,5]
y1 = [2,3,5,7,8]
y2 = [2,4,7,10,13]
plt.plot(x, y1, label="1")
plt.plot(x, y2, label="2")
plt.legend()  # 凡例をグラフにプロット
plt.title("sample : $ y = x $") #数式を入れる場合はTeX形式
plt.xlabel("X")
plt.ylabel("Y")
plt.xlim(1, 5)  # yを0-5000の範囲に限定
plt.ylim(0, 15)  # yを0-5000の範囲に限定
plt.hlines([4, 10], 2, 4, linestyles="dashed")  # y=4,10 x=2~4に破線を描画

plt.savefig('image01.png') #グラフをエクスポート
plt.show() #ここで、ここまでのグラフの設定、描画を終了

#----------散布図----------

keisankekka = len(y2)
plt.plot(x, y1, ".", label="len:%.1f" % keisankekka) #ラベルを計算結果にしたり
plt.plot(x, y2, "x", label="2")
plt.legend()  # 凡例をグラフにプロット
plt.text(1.5, 10, 'chushaku') #注釈を入れる、グラフのx、y座標を指定する
plt.savefig('image02.png') #グラフをエクスポート

#----------折れ線グラフを複数描画----------
fig, axes = plt.subplots(nrows = 2, ncols = 2, figsize=(5, 5), sharex = False) #sharex:x軸共有しない

#グラフ1
axes[0,0].plot(x, y1, label="0,0")
axes[0,0].legend() # 凡例を表示
axes[0,0].set_title('1')
axes[0,0].set_xlabel('x')
axes[0,0].set_ylabel('y')
axes[0,0].set_xlim(1, 5)
axes[0,0].set_ylim(0, 10)

axes[0,1].plot(x, y2, label="0,1")
axes[0,1].legend() # 凡例を表示
axes[0,1].set_title('2')
axes[0,1].set_xlabel('x')
axes[0,1].set_ylabel('y')
axes[0,1].set_xlim(1, 3)
axes[0,1].set_ylim(0, 15)

axes[1,0].plot(x, y2, label="1,0")
axes[1,0].legend() # 凡例を表示
axes[1,0].set_title('3')
axes[1,0].set_xlabel('x')
axes[1,0].set_ylabel('y')
axes[1,0].set_xlim(1, 3)
axes[1,0].set_ylim(0, 15)

axes[1,1].axis('off') #空白

fig.tight_layout()  # タイトルとラベルが被るのを解消
plt.savefig('image03.png') #グラフをエクスポート

xlsxを開いてcsvに値を保存

import sys
import os
import re
import glob
import csv
import win32com.client

class func():
		
	def __init__(self, load_path=''):
		
		self.dir, self.file = os.path.split(load_path)
		self.load_path = load_path

	def read_xlsx(self):

		xlApp = win32com.client.Dispatch("Excel.Application")
		xlApp.DisplayAlerts = False
		
		wb = xlApp.Workbooks.Open(self.load_path)
		sheet = wb.Worksheets("Sheet1")
		
		a = sheet.Range("A1").Value
		b = sheet.Range("B1").Value

		wb.Close()
		xlApp.Quit()
		wb = None
		xlApp = None

		if not os.path.isfile('summary.csv'):
			f = open('summary.csv', 'w')
			f.close()
			
		f = open('summary.csv', 'a', newline='')
		csvWriter = csv.writer(f)
		csvWriter.writerow([a,b])
		f.close()
		
if __name__ == '__main__':
	
	argvs = sys.argv 
	argc = len(argvs) #引数の個数
	
	if argc != 2:
		sys.exit()
	
	if re.search('.xlsx',argvs[1]):
		try:
			sheet = func(argvs[1])
			sheet.read_xlsx()
		except:
			print('Error : Input file is not supported.')
			sys.exit()
	else:
		try:
			xlsx_list = glob.glob('%s/*.xlsx' % argvs[1])
			
			if len(xlsx_list) != 0:
				for i in xlsx_list:
					sheet = func(i)
					sheet.read_xlsx()
			else:
				print('Error : Input file/folder is not supported.')
				sys.exit()
			
		except:
			print('Error : Input file is not supported.')
			sys.exit()