Driving AI Agents to Perform Data Analysis and Automated Plotting via Code
This article explores how code-driven AI agents can perform data analysis and generate data-accurate visualizations. It covers the transition from generative image models to code-based plotting, outlines a typical agent workflow for analysis tasks, details the importance of defining statistical calibers like quantiles, and provides frameworks for evaluating agent accuracy and selecting the right plotting approach.
Core Conclusion: Charts involving specific numerical values should be generated using code, while generative image models should be reserved only for decorative visuals. Regardless of the method, every chart should retain its corresponding code and data evidence to facilitate manual verification.
From “Image Generation” to “Code-Based Plotting”
When traditional Large Language Models (LLMs) handle visualization requests, they often rely on multimodal generative models. These models learn pixel distribution patterns from massive datasets and generate an approximate image based on text instructions. The resulting image may look visually striking, but data precision cannot be guaranteed. Axis ticks may be misaligned, numerical labels might be model-completed hallucinations, and line trends may not match the original data.
AI agents take a different approach. They first interpret the requirement as a set of computational steps, then write scripts to read, calculate, and plot. Every coordinate point and every bar in the chart comes from the actual computational results of the dataset, rather than model probability speculation. This approach reduces the risk of “hallucinations” in structured data scenarios and ensures consistent results when running the same dataset multiple times.
How Agents Complete an Analysis Task
Taking “parsing local inventory data and generating a visual weekly report” as an example, a typical agent workflow includes the following steps:
- Task Decomposition: The agent breaks down the instruction into a to-do list, such as reading the data source, cleaning the data, calculating quantiles, retrieving industry information, and running the plotting script.
- Loop Execution and Validation: The agent runs Python scripts via the command line, uses
pandasto read Excel or CSV files for data pivoting, and then usesmatplotlibto plot charts. The output of each step should be inspected, triggering a correction flow if errors occur. - Integrating External Information: If configured with web search or an internal knowledge base, the agent can supplement industry background. The supplementary information should be cited with sources and presented separately from local calculation results.
- Document Generation: Once all calculations and plotting are complete, the agent can call a document library to merge text analysis and charts into a PDF report.
This workflow can automatically produce a report draft, but it cannot replace human judgment. Key conclusions, statistical calibers, and chart labels still require human review.
Clarifying the Caliber of Quantiles
Quantiles are values that divide a set of ordered data into several equal parts. For example, the 50th percentile is the median, indicating that about half of the observations are no greater than it. Even with the same name like “inventory quantile,” different calibers yield different results. When writing requirements or reviewing results, at least the following must be clarified:
- Data Range: Which records are used and the length of the time window.
- Quantile Point (q): For example, 0.1, 0.5, 0.9.
- Interpolation Method: Pandas’
quantiledefaults to linear interpolation. Other libraries or manual calculations may have different defaults, leading to subtle differences in results. - Sample Size: When the sample is too small, quantiles are highly unstable.
- Missing Values and Outlier Handling: State whether missing values are deleted or filled, and whether outliers are truncated.
Example code is as follows:
import pandas as pddf = pd.read_csv("inventory.csv", parse_dates=["date"])stock = df["stock"].dropna() # Drop missing values, caliber must be stated in the reportq_levels = stock.quantile([0.1, 0.25, 0.5, 0.75, 0.9]) # Default linear interpolationcurrent = stock.iloc[-1] # Assuming data is sorted by date in ascending ordercurrent_rank = (stock <= current).mean() # Empirical quantile of the current value in the sampleprint(q_levels)print(f"Current value empirical quantile: {current_rank:.1%}")
Evaluating Agent Analysis Accuracy
Numerical performance can vary significantly among different agents, but public comparisons often lack test data and repeated experiments, making it difficult for readers to verify. This article does not provide specific platform rankings. A more reliable approach is to establish your own evaluation process:
| Evaluation Dimension | Verification Method | Pass Criteria |
|---|---|---|
| Numerical Correctness | Calculate reference answers using an independent script and compare item-by-item with agent output | Error within a pre-agreed tolerance |
| Reproducibility | Run the same input multiple times | Values are consistent, or consistent within tolerance |
| Execution Evidence | Check if code and execution logs are attached to the response | Code corresponds to conclusions |
| Caliber Transparency | Check if quantile points, interpolation methods, and sample size are noted | Caliber information is complete |
| Chart Consistency | Compare key points in the chart with calculation results | Ticks, labels, and data are consistent |
Choosing the Plotting Path
| Comparison Item | Code Plotting (matplotlib, seaborn) | Generative Image Models |
|---|---|---|
| Numerical Precision | Ticks and data points determined by calculation results | Cannot guarantee tick and data point positions |
| Reproducibility | Same script and data can reproduce the chart | Output may differ each time |
| Vector Output | Supports PDF, SVG; lossless scaling and printing | Usually bitmaps |
| Applicable Scenarios | Data charts in the main text | Covers, conceptual diagrams, decorative images |
When choosing code-based plotting, you should also pay attention to the types of charts.
