PySimpleGUI 学習:グラフ表示
2021-03-03 : 
PCクリニック
前回(2021-02-24)の記事:「PySimpleGUI 学習:プログラムの雛形」
に続いて、
PySimpleGUI27.py を使っての、グラフを表示する方法を纏めた。
先月(2021-02-10)の記事:
「PySimpleGUI ってどうかな?」で書いた、
「Tkinterを使うのであればPySimpleGUIを使ってみたらという話」
の
・・・・・
・・・・・
・ PySimpleGUIでグラフを描く」
・ PySimpleGUIのみでグラフを書く方法と・・・・・
・・・・・
・・・・・
へ行き、
・・・・・
・・・・・
PySimpleGUIでグラフを利用する場合は大まかに言って2通りあります
・ graph-elementを使って描画する
・ matplotlibを埋め込んで描画する
・・・・・
・・・・・
から、
1番目のページへ行き、
いろいろ眺めていたら、
Trinket / Demo Programs
Graph Element - Sine Wave
に辿り着いた。
ここに載っている「main.py」
# import PySimpleGUIWeb as sgこれで、
# import PySimpleGUIQt as sg
import PySimpleGUI27 as sg # PySimpleGUI を PySimpleGUI27 に。
import math
SIZE_X = 200
SIZE_Y = 100
NUMBER_MARKER_FREQUENCY = 25
def draw_axis():
graph.draw_line((-SIZE_X,0), (SIZE_X, 0)) # axis lines
graph.draw_line((0,-SIZE_Y), (0,SIZE_Y))
for x in range(-SIZE_X, SIZE_X+1, NUMBER_MARKER_FREQUENCY):
graph.draw_line((x,-3), (x,3)) # tick marks
if x != 0:
graph.draw_text( str(x), (x,-10), color='green', font='Algerian 15')
# numeric labels
for y in range(-SIZE_Y, SIZE_Y+1, NUMBER_MARKER_FREQUENCY):
graph.draw_line((-3,y), (3,y))
if y != 0:
graph.draw_text( str(y), (-10,y), color='blue')
sg.change_look_and_feel('DarkAmber') # let's add a little color
# Create the graph that will be put into the window
graph = sg.Graph(canvas_size=(400, 400),
graph_bottom_left=(-(SIZE_X+5), -(SIZE_Y+5)),
graph_top_right=(SIZE_X+5, SIZE_Y+5),
background_color='white',
key='graph')
# Window layout
layout = [[sg.Text('Example of Using Math with a Graph', justification='center', size=(50,1), relief=sg.RELIEF_SUNKEN)],
[graph],
[sg.Text('y = sin(x / x2 * x1)', font='Algerian 18')],
[sg.Text('x1'),sg.Slider((0,200), orientation='h', enable_events=True,key='_SLIDER_')],
[sg.Text('x2'),sg.Slider((1,200), orientation='h', enable_events=True,key='_SLIDER2_')]]
window = sg.Window('Graph of Sine Function', layout)
while True:
event, values = window.read()
if event is None:
break
graph.erase()
draw_axis()
prev_x = prev_y = None
for x in range(-SIZE_X,SIZE_X):
y = math.sin(x/int(values['_SLIDER2_']))*int(values['_SLIDER_'])
if prev_x is not None:
graph.draw_line((prev_x, prev_y), (x,y), color='red')
prev_x, prev_y = x, y
一応グラフ表示は可能だが、些か行数が多い!
「PySimpleGUIでグラフを描く」のページに、
公式のグラフ関係のサンプルについて
PySimpleGUIはサンプルファイルが多くて、
実装の参考になるもので役に立つサンプルがたくさんあります。
・ 公式のデモ
・ ・・・<URL>・・・
・ 公式のデモ2
・ ・・・<URL>・・・
この中から個人的に役に立つ面白いと感じたサンプルを紹介します
matplotlibとの連携
・・・・・
・・・・・
・ ・・・<URL>・・・
・ matplotlibとの連携です。
matplotlibを使ったデモはほかにもいくつかあります
この、<URL> つまり、
https://github.com/
PySimpleGUI/PySimpleGUI/blob/master/DemoPrograms/Demo_Matplotlib.py
に行った。
#!/usr/bin/env pythonこれなら、これまで<紙>が行っているコード流に近い。
from matplotlib.ticker import NullFormatter # useful for 'logit' scale
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import PySimpleGUI27 as sg ##### Python 2.7版
import matplotlib
################################ matplotlib.use('TkAgg')
"""
Demonstrates one way of embedding Matplotlib figures into
a PySimpleGUI window.
Basic steps are:
* Create a Canvas Element
* Layout form
* Display form (NON BLOCKING)
* Draw plots onto convas
* Display form (BLOCKING)
Based on information from: https://matplotlib.org/3.1.0/・・・.html
(Thank you Em-Bo & dirck)
"""
# ------------------ PASTE YOUR MATPLOTLIB CODE HERE --------------
#
# # Goal is to have your plot contained in the variable "fig"
#
# # Fixing random state for reproducibility
# np.random.seed(19680801)
#
# # make up some data in the interval ]0, 1[
# y = np.random.normal(loc=0.5, scale=0.4, size=1000)
# y = y[(y > 0) & (y < 1)]
# y.sort()
# x = np.arange(len(y))
#
# # plot with various axes scales
# plt.figure(1)
#
# # linear
# plt.subplot(221)
# plt.plot(x, y)
# plt.yscale('linear')
# plt.title('linear')
# plt.grid(True)
#
# # log
# plt.subplot(222)
# plt.plot(x, y)
# plt.yscale('log')
# plt.title('log')
# plt.grid(True)
#
# # symmetric log
# plt.subplot(223)
# plt.plot(x, y - y.mean())
# plt.yscale('symlog', linthreshy=0.01)
# plt.title('symlog')
# plt.grid(True)
#
# # logit
# plt.subplot(224)
# plt.plot(x, y)
# plt.yscale('logit')
# plt.title('logit')
# plt.grid(True)
# plt.gca().yaxis.set_minor_formatter(NullFormatter())
# plt.subplots_adjust(top=0.92, bottom=0.08, left=0.10,
# right=0.95, hspace=0.25, wspace=0.35)
# fig = plt.gcf()
#
fig = matplotlib.figure.Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(111).plot(t, 2 * np.sin(2 * np.pi * t))
# ------------------ END OF YOUR MATPLOTLIB CODE --------------------
# ------------------ Beginning of Matplotlib helper code --------------
def draw_figure(canvas, figure):
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side='top',fill='both',expand=1)
return figure_canvas_agg
# ------------------ Beginning of GUI CODE ----------------------------
# define the window layout
layout = [[sg.Text('Plot test')],
[sg.Canvas(key='-CANVAS-')],
[sg.Button('Ok')]]
# create the form and show it without the plot
window = sg.Window('Demo Application - Embedding Matplotlib In PySimpleGUI', layout, finalize=True, element_justification='center', font='Helvetica 18')
# add the plot to the window
fig_canvas_agg = draw_figure(window['-CANVAS-'].TKCanvas, fig)
event, values = window.read()
window.close()
(一部<紙>の知らなかったコードもあるが)
そもそもの問題であった、
「could not find or load the Qt platform plugin "windows"」
のエラーも起こらない。
この流儀(?)を学習しよう。
手始めに、(<紙>にとって)分かりやすいコードにしてみた:
# -*- coding: utf-8 -*-これが、基本的なコード例かな?
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import PySimpleGUI27 as sg ##### Python 2.7版
import matplotlib
'''
Demo. one way of embedding Matplotlib figures into a PySimpleGUI.
Basic steps are:
* Create a Canvas Element
* Layout form
* Display form (NON BLOCKING)
* Draw plots onto convas
* Display form (BLOCKING)
'''
# ------------------------ PASTE YOUR MATPLOTLIB CODE HERE ----------
fig = matplotlib.figure.Figure(figsize=(5, 4), dpi=100)
t = np.arange(0, 3, .01)
fig.add_subplot(221).plot(t, 2 * np.sin(2 * np.pi * t))
fig.add_subplot(224).plot(t, np.exp( t))
# ------------------------ END OF YOUR MATPLOTLIB CODE ---------------
# ------------------------ Beginning of Matplotlib helper code ----------
def draw_figure(canvas, figure):
figure_canvas_agg = FigureCanvasTkAgg(figure, canvas)
figure_canvas_agg.draw()
figure_canvas_agg.get_tk_widget().pack(side='top',fill='both',expand=1)
return figure_canvas_agg
# ------------------------ Beginning of GUI CODE ------------------------
# define the window layout
layout = [[sg.Text('Plot test')],
[sg.Canvas(key='-CANVAS-')],
[sg.Button('Ok')]]
# create the form and show it without the plot
window = sg.Window('Demo Application', layout, finalize=True,
element_justification='center')
# add the plot to the window
fig_canvas_agg = draw_figure(window['-CANVAS-'].TKCanvas, fig)
event, values = window.read()
window.close()
本日はここまで。
PySimpleGUI の学習は続く。
見ていただいた序でとは厚かましい限りですが、
お帰りに投票して頂けるとなお嬉しいです。 ⇒

201211
スポンサーサイト