# Fix "AttributeError: 'FigureCanvasAgg' object has no attribute 'tostring_rgb'"

Yes. An agent replaces tostring_rgb with buffer_rgba, fixes the NumPy call beside it that fails next, and proves the image array is the same, pixel for pixel.

[Run this on Rush](https://cloud.getrush.ai/run/fix-figurecanvasagg-tostring-rgb-attribute-error/matplotlib/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

Matplotlib 3.10 removed `FigureCanvasAgg.tostring_rgb()`, the method machine-learning code used for years to turn a figure into a pixel array for TensorBoard. The agent finds each call and what executes it. In jaywalnut310/glow-tts there are two, in `utils.py`: `plot_spectrogram_to_numpy` on line 98 and `plot_alignment_to_numpy` on line 127, both the same statement, `np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')`, followed by a reshape to height, width and three channels. `train.py` calls them inside the training loop to build the images it hands to `utils.summarize`, which passes them to the summary writer's `add_image`. So the error does not appear at import or at start-up. It appears at the first logging step, after data loading and model set-up have already been paid for.

The line holds two removed APIs, and fixing the one in the title exposes the other. `np.fromstring` with `sep=''` was NumPy's binary mode; current NumPy raises `ValueError: The binary mode of fromstring is removed, use frombuffer instead`. The agent establishes both by running the two functions as written against two environments in the sandbox. With Matplotlib 3.9 and NumPy 1.26 they return a 480 by 640 by 3 array and print two warnings, one saying `tostring_rgb` was deprecated in Matplotlib 3.8 and will be removed in 3.10, the other that the binary mode of `fromstring` is deprecated. With current releases of both, the call fails on `tostring_rgb` first.

The replacement is `np.asarray(fig.canvas.buffer_rgba())` with the alpha channel sliced off, `[..., :3]`. Before proposing it the agent checks equivalence where both forms exist: on Matplotlib 3.9 it renders the same figure, takes the array both ways, and compares every element. They are equal, with the same shape and dtype, so what TensorBoard receives is unchanged. It also checks a property the old code had and the new expression lacks. The old path copied the pixels into a new bytes object. `buffer_rgba` exposes the canvas's own memory, and the functions call `plt.close()` on the next line, so the agent adds `.copy()` and explains that the returned array should not depend on a figure that has been closed.

This repository pins nothing. It has no requirements file, and the README lists the environment the authors used, including Python 3.6.9 and NumPy 1.16.4, as prose. A fresh install therefore gets current Matplotlib and NumPy and meets this error. The agent runs the two fixed functions under both environments and reports that the training loop itself was not run, since it needs the dataset and a Cython build step the README describes. It proposes a small requirements file with lower bounds that match what the fixed code needs, as a separate commit the maintainers can decline.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "After upgrading dependencies, this project fails with \"AttributeError: 'FigureCanvasAgg' object has no attribute 'tostring_rgb'\". Find every call to tostring_rgb and tostring_argb on a Matplotlib canvas, and every use of np.fromstring in binary mode (sep='' or no sep) or ndarray.tostring next to them. For each call say what executes it and when: at import, at start-up, or only at a logging or plotting step during a long job. Create two environments: one with Matplotlib 3.9 and NumPy 1.26, where the old calls still work with deprecation warnings, and one with the current releases of both. Run the affected functions in each, on a small array of the right shape, without running the full training or pipeline, and save the warnings and errors. Replace the calls with np.asarray(fig.canvas.buffer_rgba()) and drop the alpha channel. In the older environment, render the same figure once and prove the new array equals the old one element for element, with the same shape and dtype. Make sure the returned array does not keep referring to the canvas buffer after the figure is closed. Then run the fixed functions in both environments with warnings turned into errors. Do not change the plots themselves. If the project does not pin its dependencies, say so and propose minimum versions in a separate commit. Report which parts of the project you could not run and why. Open a pull request with the outputs from both environments, the equality check and what you left alone.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request that changes two statements in `utils.py`, one in each plotting function, and optionally adds a requirements file in a second commit. The description shows four runs: the original functions in the older environment with their two warnings, the original functions in the current environment with the error, and the fixed functions in each with warnings treated as errors. Between them is the equality check, stated as the shape, the dtype and the result of comparing the arrays.

A reviewer checks the slice and the copy. Dropping the alpha channel is what keeps the array at three channels, which is what `add_image` is told to expect by `dataformats='HWC'` in `summarize`, and the copy is what makes the function safe to call in a loop that closes each figure. They should read the limits as stated: the plotting functions are executed on a synthetic array and no training step runs, so the claim is that this error is gone and the images are unchanged, not that training now completes on current dependencies.

## Run it on every week

Research code that pins nothing changes behaviour whenever its dependencies release, and nobody learns of it until a job fails hours in. A weekly check moves that discovery to a pull request. Add an automation on the Project with a `schedule` trigger, a `cron` for the hour you want and your `timezone`. Give it a prompt that installs the project with current dependencies, runs its entry points on small synthetic inputs with warnings shown, and fixes what the newest releases broke, following the request above for anything involving plotting.

Deprecation warnings are the early signal. The message for this removal was printed for two minor versions before the method went away, and a weekly run that reports new warnings gives you that long to act. The automation's max runs per hour bounds the work if you attach the same schedule to many Projects.

## Why run it on Rush?

Proving that a replacement draws the same picture needs an environment where both the old and the new call exist, and proving the failure needs one where the old call is gone. Building two environments and rendering figures in each is quick in a sandbox and a nuisance on a workstation whose one environment took an afternoon to get working. The agent does it without touching yours, and the session keeps the output of each run.

The cost of this bug is also out of proportion to its size. Two lines fail, but they fail at a logging step inside a job that may have queued for a GPU. Catching the removal from a scheduled run on a small input, and getting back a change with an element-for-element check, costs less than one lost training start.

## Frequently asked questions

### What replaces canvas.tostring_rgb()?

`canvas.buffer_rgba()`, which returns the rendered pixels with four channels. Wrap it in `np.asarray(...)` to get an array of shape height by width by 4, and slice `[..., :3]` to drop alpha. Call `canvas.draw()` first, as the old code did.

### Do I still need the reshape?

No. The array from `buffer_rgba` already has its height and width, so the `get_width_height()` reshape that followed `tostring_rgb` can go.

### Why does np.fromstring fail after I fix the Matplotlib call?

Because the same line used NumPy's binary mode of `fromstring`, which current NumPy has removed in favour of `np.frombuffer`. With `buffer_rgba` you need neither function: `np.asarray` reads the buffer directly.

### Can I pin Matplotlib below 3.10 instead?

Yes, and it works for as long as that release installs on your Python. It postpones the change and keeps you on a version that prints the deprecation warning at every plot. The edit is two lines, so most projects are better served by making it.

## More Matplotlib jobs

- [Fix "TypeError: gca() got an unexpected keyword argument 'projection'" in Matplotlib 3D Plots](https://getrush.ai/run/fix-gca-got-an-unexpected-keyword-argument-projection/matplotlib/)
- [Fix "AttributeError: module 'matplotlib.cm' has no attribute 'get_cmap'" on Matplotlib 3.9](https://getrush.ai/run/fix-matplotlib-cm-get-cmap-attribute-error/matplotlib/)
- [Fix "OSError: 'seaborn' is not a valid package style" in Matplotlib](https://getrush.ai/run/fix-seaborn-is-not-a-valid-package-style/matplotlib/)

## More jobs like this: Upgrade dependencies weekly

- [Fix "AttributeError: 'Graph' object has no attribute 'node'" in NetworkX](https://getrush.ai/run/fix-graph-object-has-no-attribute-node/networkx/)
- [Fix grpc.WithInsecure Is Deprecated (SA1019) in a Go gRPC Service](https://getrush.ai/run/fix-grpc-withinsecure-is-deprecated/grpc-go/)
- [Fix "npm warn deprecated gulp-util: gulp-util is deprecated" in a Gulp Build](https://getrush.ai/run/fix-gulp-util-is-deprecated-warning/gulp/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
