politicnewsbusterinsiderpostreview

Tuesday, 31 January 2023

[New post] Automation production of a series of charts in Excel format is easy with a bit of Python

Site logo image Colin Paice posted: " We use a building, and have a .csv files of the power used every half hour for the last three months. We wanted to produce charts of the showing usage, for every Monday, and for every week throughout the year. Creating charts in a spreadsheet,manually " ColinPaice

Automation production of a series of charts in Excel format is easy with a bit of Python

Colin Paice

Jan 31

We use a building, and have a .csv files of the power used every half hour for the last three months. We wanted to produce charts of the showing usage, for every Monday, and for every week throughout the year. Creating charts in a spreadsheet,manually creating a chart, and adding data to the series, soon got very boring. It was much more interesting to automate this. This blog post describes how I used Python and xlsxWwriter to create an Excel format spread sheet - all this from Linux.

Required output

Because our building is used by different groups during the week, I wanted to have

  • a chart for "Monday" for one group of users, "Tuesday" for another group of users, etc. This would allow me to see the typical profile, and make sure the calculated usage was sensible.
  • A chart on a week by week basis. So a sheet and chart for each week.
  • Automate this so, I just run a script to get the spread sheet and all of the graphs.

From these profiles we could see that from 0700 to 0900 every day there was a usage hump - a timer was turning on the outside lights, even though no one used the building before 1000!

Summary of the code

  • Read a CSV file in to memory
  • Create the workbook and add a sheet
  • Create a chart template
  • Create a chart for every day of the week
  • Build up the first row of data labels as a header row
  • Convert a string to a data time
  • Write each row
  • Create a sheet for each week
  • Add data range to each chart
  • Writing a formula
  • Save, clean up and end

Reading the csv file

I used

import csv fn = "HF.csv" with open(fn, newline='') as csvfile:     reader = csv.DictReader(csvfile)    for row in reader:       # get the column lables       keys = row.keys() ...

Create the workbook and add a sheet

This opens the specified file chart_scatter.xlsx, for output, and overwrites any previous data.

import xlsxwriter ... workbook = xlsxwriter.Workbook('chart_scatter.xlsx') data= workbook.add_worksheet("Data")

Create a chart template

I used a Python function to create a standard chart with common configuration, so all charts had the same scale, and look and feel.

def default_chart(workbook,title):    chart1 = workbook.add_chart({'type': 'scatter'})    # Add a chart title and some axis labels.    chart1.set_title ({'name': title})    chart1.set_x_axis({           'time_axis':  True,           'num_format': 'hh:mm',           'min': 0,            'max': 1.0,           'major_unit':1/12., # 2 hours           'minor_unit':1.0/24.0, # every hour           'major_gridlines': {             'visible': True,             'line': {'width': 1.25, 'dash_type': 'long_dash'},              },           'minor_tick_mark': 'inside'           })    chart1.set_y_axis({           'time_axis':  True,           'min': 0,            'max': 7.0, # so they all have the same max value           'major_unit':1,           'minor_unit':0,           'minor_tick_mark': 'inside'           })          #chart1.set_y_axis({'name': 'Sample length (mm)'})    chart1.set_style(11)  # I do not know what this does    chart1.set_size({'width': 1000, 'height': 700})    return chart1

Create a chart for every day of the week

This creates a sheet (tab) for each day of the week, creates a chart, and attaches the chart to the sheet.

days=['Mon','Tue','Wed','Thu','Fri','Sat','Sun'] days_chart = [] for day in days:       c=default_chart(day) # create chart       days_chart.append(c)     # build up list of days       # add a sheet with name of the day of the week        wb =workbook.add_worksheet(day) # create a sheet with name        wb.insert_chart('A1',c)  # add chart to sheet 

Build up the first row of data labels as a header row

This processes the CSV file opened above and writes each key to the first row of the table.

In my program I had some logic to change the headers from the csv column name to a more meaningful value.

fn = "HF.csv" with open(fn, newline='') as csvfile:     reader = csv.DictReader(csvfile)     # read the header row from the csv       row  = next(reader, None)     count = LC.headingRow(workbook,data,summary,row)     keys = list(row.keys())     for i,j in enumerate(keys):        #  'i' is is the position        # 'j' is the value        heading = j         # optional logic to change heading         # write data in row 0, column i        data.write_string(0,i,heading) # first row an column of the data     # add my own columns header     data.write_string(0,count+1,"Daily total")           

Convert a string to a data time

d = row['Reading Date'] # 01/10/2022 dd,mm,yy  = d.split('/') dt = datetime.fromisoformat(yy+'-'+mm+'-'+dd) weekday = dt.weekday()	 # make a nice printable value dow =days[weekday] + ' ' + dd + ' ' + mm + ' ' + yy row['Reading Date'] = datetime.strptime(d,'%d/%m/%Y')

Write each row

This takes the data items in the CSV file and writes them a cell at a time to the spread sheet row.

I have some cells which are numbers, some which are strings, and one which is a date time. I have omitted the code to convert a string to a date time value

ddmmyy  = workbook.add_format({'num_format': 'dd/mm/yy'}) for row in reader:     keys = row.keys()     items = list(row.items())       for i,j  in enumerate(items):  # ith and (key,value)        j =j[1] # get the value        # depending on data type - used appropriate write method        if isinstance(j,datetime):           data.write_datetime(r,i, j,ddmmyy)        else:        if j[0].isdigit():              dec = Decimal(j)            data.write_number(r,i,dec)             sum = sum + dec         else:               data.write(r,i ,j) 

Create a sheet for each week

 if (r == 1 or dt.weekday() == 6): # First record or Sunday  # create a new work sheet, and chart      temp = workbook.add_worksheet(dd + '-' +mm)     chart1 = workbook.add_chart({'type': 'scatter'})     chart1 = default_chart('Usage for week starting '+ ...)     # put chart onto the sheet     temp.insert_chart('A1', chart1)   

Add data range to each chart

This says create a chart with

  • data name from the date value in column 3 of the row - r is row number
  • use the column header from data sheet row 0, column 5; to row 0 column count -1
  • use the vales from from r, column 5 to row r ,column count -1
  • pick the colour depending on the day colours[] is an array of colours ["red","blue"..]
  • picks a marker type based on week day from an array ["square","diamond"...]
# r is the row number in the data  chart1.add_series({          'name':       ['Data',r,3],          #  field name is row 0 cols 5 to ...           'categories': ['Data',0,5,0,count-1],           # data is in row r - same range 5 to  ,,,          'values':     ['Data',r,5,r,count-1],           # pick the colour and line width           'line':       {'color': colours[weekday],"width" :1 },          # and the marker          'marker':     {'type': markers[weekday]}        })

Write a cell formula

You can write a formula instead of a value. You have to modify the formula for each row and column.

In a spread sheet you can create a formula, then use cut and paste to copy it to many cells. This will change the variables. If you have for cell A1, =SUM(A2:A10) then copy this to cell B2, the formula will be =SUM(B3:B11).

With xlsxWriter you have to explicitly code the formula

worksheet.write_formula('A1', '{=SUM(A2:A10)}') worksheet.write_formula('B2', '{=SUM(B3:B11)}')

Save, clean up and end

I had the potential to hide columns - but then they did not display.

I made the column widths fit the data.

# hide boring stuff # data.set_column('A:C',None,None,{'hidden': 1})  # Make columns narrow  data.set_column('D:D', 5)  # Just Column d     data.set_column('F:BA', 5)  # Columns F-BA 30.     workbook.close()        exit(0)
Comment
Like
Tip icon image You can also reply to this email to leave a comment.

Unsubscribe to no longer receive posts from ColinPaice.
Change your email settings at manage subscriptions.

Trouble clicking? Copy and paste this URL into your browser:
http://colinpaice.blog/2023/01/31/automation-production-of-a-series-of-charts-in-excel-format-is-easy-with-a-bit-of-python/

Powered by WordPress.com
Download on the App Store Get it on Google Play
at January 31, 2023
Email ThisBlogThis!Share to XShare to FacebookShare to Pinterest

No comments:

Post a Comment

Newer Post Older Post Home
Subscribe to: Post Comments (Atom)

BREAKING: North Carolina automotive group acquires 7 Upstate dealerships

Breaking news from GSA Business Report Click here to view this message in a browser window. ...

  • Search Engine Watch
    Search Engine Watch ...
  • Search Engine Watch
    Search Engine Watch Seven Google alerts SEOs need to stay on top of everything! Posted: 25 Jan 2022...
  • Search Engine Watch
    Search Engine Watch ...
  • https://paxorex.blogspot.com
  • https://acciyo.blogspot.com
  • https://sunbrew.blogspot.com
  • https://readingvox.blogspot.com
  • https://neextdraft.blogspot.com
  • https://udimy.blogspot.com
  • https://arcieve.blogspot.com
  • https://diabetesmail.blogspot.com
  • https://quiltingmail.blogspot.com
  • https://downloadallyouwanttutorials.blogspot.com
  • https://increasingmarketingsystem.blogspot.com
  • https://skysportingnewsnationspinquirer.blogspot.com
  • https://politicnewsbusterinsiderpostreview.blogspot.com
  • https://javascripttrendlist.blogspot.com
  • https://teraqiitatail.blogspot.com
  • https://bigpalacenews.blogspot.com
  • https://executivetowernews.blogspot.com
  • https://magnificentplannews.blogspot.com
  • https://businessinboard.blogspot.com
  • https://patriotsscience.blogspot.com
  • https://allinonequantumleap.blogspot.com
  • https://foodandrecipefusion.blogspot.com
  • https://newsletterforeveryone.blogspot.com
  • https://snacksrobinhood.blogspot.com
  • https://dailynewslettersph.blogspot.com
  • https://rankedrama.blogspot.com
  • https://oschinanet.blogspot.com
  • https://nourich.blogspot.com
  • https://phnewsnet.blogspot.com
  • https://structuresusingc.blogspot.com
  • https://foodubers.blogspot.com
  • https://genuinequality.blogspot.com
  • https://techdigitalmedia.blogspot.com
  • https://entertainmenhubtbiz.blogspot.com
  • https://sportsbookwire.blogspot.com
  • https://societycast.blogspot.com
  • https://lifestylesportsreturn.blogspot.com
  • https://natureimpactfactor.blogspot.com
  • https://artnetworth.blogspot.com
  • https://entrepreneurexamples.blogspot.com
  • https://cryptomarketbase.blogspot.com
  • https://btsbiot.blogspot.com
  • https://sexybinikis.blogspot.com
  • https://foreignexchangecurrency.blogspot.com
  • https://classifiedexample.blogspot.com
  • https://bookboons.blogspot.com
  • https://writingdate.blogspot.com
  • https://wamios.blogspot.com
  • https://justmightdiy.blogspot.com
  • https://playfreeonlinegamesmore.blogspot.com
  • https://healthlinefitnessfirst.blogspot.com
  • https://snaptikvideodownloader.blogspot.com
  • https://pokemonunitepc.blogspot.com
  • https://neverthelesskdrama.blogspot.com
  • https://coolantioniq.blogspot.com
  • https://hackerploit.blogspot.com
  • https://ballbreakdown.blogspot.com
  • https://flixsterio.blogspot.com
  • https://fortnitebattleroyaletrack.blogspot.com
  • https://manilaplus.blogspot.com
  • https://davaoplus.blogspot.com
  • https://tutorialsfiles.blogspot.com
  • https://mondaymorningcookingclub.blogspot.com
  • https://gymnearmee.blogspot.com
  • https://windows26.blogspot.com
  • https://millionaireinvest.blogspot.com
  • https://latestkhmernews.blogspot.com
  • https://latestisraelnews.blogspot.com
  • https://latestaustralianews.blogspot.com
  • https://latestirannews.blogspot.com
  • https://latestjapannews.blogspot.com
  • https://latestsaudinews.blogspot.com
  • https://latestfreecourse.blogspot.com
  • https://ikeafurnitureaccessories.blogspot.com
  • https://makeupandbeautyproduct.blogspot.com
  • https://latestpets.blogspot.com
  • https://topecommerceniches.blogspot.com
  • https://latesttexasnews.blogspot.com
  • https://latestufcgame.blogspot.com
  • https://tipweightlossfast.blogspot.com
  • https://latestcancercure.blogspot.com
  • https://philsys.blogspot.com
  • https://phoramensoba.blogspot.com
  • https://latestcupcakes.blogspot.com
  • https://latestgivex.blogspot.com
  • https://latestlottoresult.blogspot.com
  • https://downloadarchived.blogspot.com
  • https://doesports.blogspot.com

Search This Blog

  • Home

About Me

politicnewsbusterinsiderpostreview
View my complete profile

Report Abuse

Labels

  • 【ANDROID STUDIO】ViewModel Two Way Data Binding
  • 【FLUTTER ANDROID STUDIO and IOS】 Cupertino TabScaffold
  • 【FLUTTER ANDROID STUDIO and IOS】 Expenses App
  • 【FLUTTER ANDROID STUDIO and IOS】 Explicit Animations
  • 【FLUTTER ANDROID STUDIO and IOS】 PDF Viewer
  • 【FLUTTER ANDROID STUDIO and IOS】 productivity timer
  • 【FLUTTER ANDROID STUDIO and IOS】 SimpleDialog
  • 【FLUTTER ANDROID STUDIO and IOS】bidirectional swipable or slidable sqflite with remote http using dio
  • 【FLUTTER ANDROID STUDIO and IOS】bloc design pattern
  • 【FLUTTER ANDROID STUDIO and IOS】bluetooth
  • 【FLUTTER ANDROID STUDIO and IOS】Call Android Java Code
  • 【FLUTTER ANDROID STUDIO and IOS】card selector
  • 【FLUTTER ANDROID STUDIO and IOS】change the chart dynamically using provider state management
  • 【FLUTTER ANDROID STUDIO and IOS】chip
  • 【FLUTTER ANDROID STUDIO and IOS】CircularProgressIndicator
  • 【FLUTTER ANDROID STUDIO and IOS】credit card view
  • 【FLUTTER ANDROID STUDIO and IOS】CRUD Streams
  • 【FLUTTER ANDROID STUDIO and IOS】DropdownButton
  • 【FLUTTER ANDROID STUDIO and IOS】dynamic event calendar management
  • 【FLUTTER ANDROID STUDIO and IOS】Endless ListView
  • 【FLUTTER ANDROID STUDIO and IOS】face detection and recognition using machine learning vision
  • 【FLUTTER ANDROID STUDIO and IOS】Fetch Data From The Internet
  • 【FLUTTER ANDROID STUDIO and IOS】Firebase Firestore Realtime CRUD operation
  • 【FLUTTER ANDROID STUDIO and IOS】folding cell
  • 【FLUTTER ANDROID STUDIO and IOS】Fuzzy search list initially translated from Fusejs
  • 【FLUTTER ANDROID STUDIO and IOS】GETX State Management
  • 【FLUTTER ANDROID STUDIO and IOS】giffy dialog
  • 【FLUTTER ANDROID STUDIO and IOS】IconButton
  • 【FLUTTER ANDROID STUDIO and IOS】leaflet map with marker popup
  • 【FLUTTER ANDROID STUDIO and IOS】load csv
  • 【FLUTTER ANDROID STUDIO and IOS】Measures Converter
  • 【FLUTTER ANDROID STUDIO and IOS】Multiple Files For Each Screen
  • 【FLUTTER ANDROID STUDIO and IOS】Navigate With Named Routes
  • 【FLUTTER ANDROID STUDIO and IOS】Nesting Rows and Columns
  • 【FLUTTER ANDROID STUDIO and IOS】notifications in background handling with Workmanager
  • 【FLUTTER ANDROID STUDIO and IOS】Packing Widgets
  • 【FLUTTER ANDROID STUDIO and IOS】Parsin JSON In The Background
  • 【FLUTTER ANDROID STUDIO and IOS】Parsing Blogger or Blogspot RSS Feeds in Flutter
  • 【FLUTTER ANDROID STUDIO and IOS】rating dialog
  • 【FLUTTER ANDROID STUDIO and IOS】restful calls with ajax
  • 【FLUTTER ANDROID STUDIO and IOS】Reverse and Stop Animations
  • 【FLUTTER ANDROID STUDIO and IOS】reviews slider
  • 【FLUTTER ANDROID STUDIO and IOS】RxDart BloC
  • 【FLUTTER ANDROID STUDIO and IOS】Scan Text and Barcodes Recognition and Detection with ML Kit
  • 【FLUTTER ANDROID STUDIO and IOS】scratch card
  • 【FLUTTER ANDROID STUDIO and IOS】SQflite and mobx with Cache log
  • 【FLUTTER ANDROID STUDIO and IOS】sqlite task manager Any Task Any Goal Get Things Done
  • 【FLUTTER ANDROID STUDIO and IOS】Staggered Animation
  • 【FLUTTER ANDROID STUDIO and IOS】staggered grid view
  • 【FLUTTER ANDROID STUDIO and IOS】Stateful Send Data To A New Screen
  • 【FLUTTER ANDROID STUDIO and IOS】text to speech
  • 【FLUTTER ANDROID STUDIO and IOS】Tween Animation
  • 【FLUTTER ANDROID STUDIO and IOS】Typehead autocompletion textfield library
  • 【FLUTTER ANDROID STUDIO and IOS】video recorder and picker and image picker
  • 【GAMEMAKER】 Enemy Path Finding
  • 【GAMEMAKER】Allowing a Player to Get In or Out of the Drivable Vehicle
  • 【GAMEMAKER】Card battle
  • 【GAMEMAKER】Character Stats Progression Upgrade
  • 【GAMEMAKER】Destructable Terrain
  • 【GAMEMAKER】Dice Roll
  • 【GAMEMAKER】Fishing_Mini_Game
  • 【GAMEMAKER】HUD show spells
  • 【GAMEMAKER】Lives
  • 【GAMEMAKER】Pong Retro Game Remake
  • 【GAMEMAKER】Positional Audio
  • 【GAMEMAKER】Retro Brick and Ball Game Remake
  • 【GAMEMAKER】Simple Battle System
  • 【GAMEMAKER】Simple Game Quest
  • 【GAMEMAKER】sokoban Designing Levels a room with string or text gamemaker with http get
  • 【GAMEMAKER】sokoban pushable object
  • 【GAMEMAKER】Speech bubble typewriter alert text effect
  • 【GAMEMAKER】Tank Trax with wind simulation remake
  • 【GAMEMAKER】write text files that can be downloaded and processed
  • 【LARAVEL and FLUTTER ANDROID STUDIO and IOS】Authentication System in Flutter with Laravel Passport
  • 【LARAVEL and FLUTTER ANDROID STUDIO and IOS】GETX and Dio CRUD Create Read Update Delete
  • 【LARAVEL and FLUTTER ANDROID STUDIO and IOS】GETX and GETX STORAGE CRUD Create Read Update Delete
  • 【LARAVEL and FLUTTER ANDROID STUDIO and IOS】IndexedStack Keep State(Avoid to Rebuild)
  • 【LARAVEL and FLUTTER ANDROID STUDIO and IOS】Laravel Pagination infinite scroll load more
  • 【LARAVEL and FLUTTER ANDROID STUDIO and IOS】Uploading a File to a Server from Flutter Using a Multi-Part (form-data) POST Request
  • 【LARAVEL PHP and FLUTTER ANDROID STUDIO and IOS】dynamic multiple text field
  • 【PYTHON OPENCV】 Face detection using dlib frontal face detector
  • 【PYTHON OPENCV】Cat face detection using haar feature-based cascade classifiers
  • 【PYTHON OPENCV】Face detection using cvlib face detector (uses DNN OpenCV face detector)
  • 【PYTHON OPENCV】Face detection using dlib CNN face detector using a pre-trained model
  • 【PYTHON OPENCV】Face detection using dlib frontal face detector
  • 【PYTHON OPENCV】Face detection using haar feature-based cascade classifiers
  • 【PYTHON OPENCV】Face detection using OpenCV DNN face detector
  • 【PYTHON OPENCV】Image classification using OpenCV CNN module SqueezeNet and caffe pre trained models
  • 【PYTHON OPENCV】This script makes used of dlib library to calculate the 128D descriptor to be used for face recognition and compare the faces using some distance metrics
  • 【PYTHON OPENCV】Training a linear regression model using Keras
  • 【PYTHON】Cross Validation Regression R2
  • 【REDUX and VANILLA JS】 CRUD
  • 【Visual Studio vbnet】 Delete All
  • 【Visual Studio Visual Csharp】Item Color
  • 【VISUAL VB NET】Enumerate Windows
  • 【VISUAL VB NET】Export HTML table to excel any format xls
  • 【VISUAL VB NET】File Properties
  • 【VISUAL VB NET】Monitor StandBy
  • 【VISUAL VB NET】Mouse Position
  • 【VISUAL VB NET】MS Word
  • 【VISUAL VB NET】Mutex
  • 【VISUAL VB NET】Panel Gradient
  • 【VISUAL VB NET】Print
  • 【VISUAL VB.NET】Admin Check
  • 【VISUAL VB.NET】Calendar
  • 【VISUAL VB.NET】Convert To Hex
  • 【VISUAL VB.NET】Create Desktop Shortcut
  • 【VISUAL VB.NET】Create File and Write File
  • 【VISUAL VB.NET】Enumerate_network_resources
  • 【VISUAL VB.NET】File Dates Info
  • 【VISUAL VB.NET】Firewall Enable or Disable
  • 【VISUAL VB.NET】Get DiskFreeSpace
  • 【VISUAL VB.NET】Get_computer_name
  • 【VISUAL VB.NET】Get_processor_type
  • 【Vuejs】 bind the values ​​of parent and child components in two directions
  • 【Vuejs】 book management (use directive and filter)
  • 【VUEJS】 seamless carousel effect
  • 【Vuejs】 Weekly Expenses app with chart js
  • 【VUEJS】element ui audio player functions
  • 【VUEJS】photo-sphere-viewer 360°×180° panoramic plug-in to simulate VR viewing and room switching
  • 【Vuejs】realtime geolocation tracking with leaflets and firebase database
  • 【Vuejs】Response speed test tool
  • and SQLite
  • and weapon
  • BLoCs
  • change HP
  • Face detection using face_recognition CNN face detector (internally calls dlib CNN face detector)
  • Gold
  • inventory
  • which is based on Histogram of Oriented Gradients (HOG) features and a linear classifier in a sliding window detection approach
  • xlsx
  • xml
  • XP

Blog Archive

  • August 2023 (1890)
  • July 2023 (2818)
  • June 2023 (2887)
  • May 2023 (3025)
  • April 2023 (2803)
  • March 2023 (2973)
  • February 2023 (2644)
  • January 2023 (2760)
  • December 2022 (2650)
  • November 2022 (2615)
  • October 2022 (2585)
  • September 2022 (2497)
  • August 2022 (2502)
  • July 2022 (2522)
  • June 2022 (2639)
  • May 2022 (2318)
  • April 2022 (2361)
  • March 2022 (2365)
  • February 2022 (2208)
  • January 2022 (2359)
  • December 2021 (2475)
  • November 2021 (3152)
  • October 2021 (3245)
  • September 2021 (3145)
  • August 2021 (3261)
  • July 2021 (3191)
  • June 2021 (3123)
  • May 2021 (3027)
  • April 2021 (2578)
  • March 2021 (1895)
  • February 2021 (1363)
  • January 2021 (1524)
  • December 2020 (916)
Powered by Blogger.