Friday, November 24, 2023

Generate plot chart from an AutoCAD table using Python for AutoCAD

 

The tools we need are matplotlib and pandas

 Step 1, is to create a pandas dataframe from an AutoCAD table, the structure is a dictionary {header : [data array]}. We’ll need to create a map (dictionary) of our headers so we can access them later. Next, iterate the data cells and put them in the appropriate bucket

 Step 2, setup our plot configuration, setup our colors. Note, we need to make sure the column we want to plot is the correct data type, if you’ll notice the astype cast. Run the plot

 Optional step 3, insert the result as a raster image

 here's the code

import PyRx as Rx
import PyGe as Ge
import PyGi as Gi
import PyDb as Db
import PyAp as Ap
import PyEd as Ed
import traceback

import matplotlib.pyplot as plt
from matplotlib.pyplot import savefig
import numpy as np
import pandas as pd


# create a dict to hold the headers
# create a dataframe {header : [data]}
def createDataFromTable(id : Db.ObjectId):
   
    data = {}
    header = {}
    table = Db.Table(id)

    # save header row so we can lookup the header name while looping the rows
    range = table.cellRange()
    range.topRow = 1
    range.bottomRow = 1

    for cell in table.getIterator(range):
        key = table.textStringFmt(cell, Db.FormatOption.kIgnoreMtextFormat)
        header[cell[1]] = key
        data[key] = []
       
    # iterate data rows, an put the data in our data map
    range = table.cellRange()
    range.topRow = 2

    for cell in table.getIterator(range):
        key = header[cell[1]]
        value = table.textStringFmt(cell, Db.FormatOption.kIgnoreMtextFormat)
        data[key].append(value)

    return pd.DataFrame(data)
       
       
def PyRxCmd_doit():
    try:
        es = Ed.Editor.entSel("\nSelect a table: ", Db.Table.desc())
        if es[0] != Ed.PromptStatus.eNormal:
            print("oof")
            return
       
        params = {
            "text.color": "crimson",
            "xtick.color": "crimson",
            "ytick.color": "crimson",
            "axes.edgecolor": "crimson",
            "axes.labelcolor": "crimson",
            "figure.facecolor": "crimson"}
       
        plt.rcParams.update(params)
       
        plt.xlabel("Item")
        plt.ylabel("Cost")
        plt.title("Cost per item")
 
        df = createDataFromTable(es[1])
        df['Unit']=df['Unit'].astype(float)
       
        df["Unit"].plot.bar()
        savefig("demo.png", transparent=True)
        plt.clf()# clear
       
        #todo insert as image
        print("yay")
    except Exception as err:
        traceback.print_exception(err)



No comments:

Post a Comment

TraceBoundary sample in Python for AutoCAD

    import traceback from pyrx_imp import Rx from pyrx_imp import Ge from pyrx_imp import Gi from pyrx_imp import Db from pyrx_imp...