LoginSignup
4
2

More than 1 year has passed since last update.

matplotlib: エクセルからデータを読み取り描画する事例

Last updated at Posted at 2022-07-18

はじめに

久しぶりの投稿になります。
最近、エクセルからデータを読み取ってmatplotlibで作図する必要が生じたので、その再作成したPythonプログラムを残しておこうと思います。

作例

まず、作例として、元データとなるエクセルの表と作成したグラフを示します。

Screen Shot 2022-07-18 at 8.51.18.png

fig_freq.jpg

プログラム

上に示したエクセルの表から、2カラム目(B列)、9カラム目(I列)、10カラム目(J列)の4行目から17行目までを読み取り、グラフにしています。
グラフは、機械による励振振動数を示すもので、fillを用いてハッチングにより
その範囲を表示しています。

import openpyxl
import numpy as np
import matplotlib.pyplot as plt


def drawfig(fmin,fmax,item):
    fsz=10
    xmin=0 ; xmax=150; dx=10
    ymin=0; ymax=15; dy=1
    iw=10
    ih=3
    plt.figure(figsize=(iw,ih),facecolor='w')
    plt.rcParams['font.size']=fsz
    plt.rcParams['font.family']='sans-serif'
    plt.subplots_adjust(left=0.25,right=0.95)
    tstr='Exciting frequency'
    plt.xlim([xmin,xmax])
    plt.ylim([ymax,ymin])
    plt.xlabel('Frequency (Hz)')
    plt.ylabel('')
    plt.xticks(np.arange(xmin,xmax+dx,dx))
    plt.yticks(np.arange(ymin,ymax+dy,dy))
    plt.grid(color='#999999',linestyle='solid')
    plt.title(tstr,loc='left',fontsize=fsz)

    n=len(item)
    yax=np.arange(1,n+1,1)
    plt.yticks(yax,item)
    n=len(item)
    ds=0.3
    for i in range(0,n):
        y0=i+1
        x1,x2=fmin[i],fmax[i]
        y1,y2=y0-ds,y0+ds
        xx=np.array([x1,x2,x2,x1])
        yy=np.array([y1,y1,y2,y2])
        plt.fill(xx,yy,color='#000080',fill=None, hatch='////')


    #plt.tight_layout()
    fnameF='fig_freq.jpg'
    plt.savefig(fnameF, dpi=200, bbox_inches="tight", pad_inches=0.1)
    #plt.show()

def main():
    fnameR='frequency.xlsx'
    wb = openpyxl.load_workbook(fnameR, data_only=True)
    sheet = wb['frequency']
    n=14
    item=np.full(n,'a',dtype=object)
    fmin=np.zeros(n,dtype=np.float64)
    fmax=np.zeros(n,dtype=np.float64)
    for i,rw in enumerate(range(4,18)):
        item[i]=sheet.cell(row=rw,column=2).value
        fmin[i]=sheet.cell(row=rw,column=9).value
        fmax[i]=sheet.cell(row=rw,column=10).value

    for i in range(0,n):
        print('{0:6.2f} {1:6.2f} {2:s}'.format(fmin[i],fmax[i],item[i]))

    drawfig(fmin,fmax,item)


#---------------
# Execute
#---------------
if __name__ == '__main__': main()

以上

4
2
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
4
2