Matplotlib绘图出现AttributeError及数据处理问题求助
Hey there! Let's work through your Matplotlib issues one by one, I've got you covered.
1. 解决AttributeError: 'FigureCanvasInterAgg' object has no attribute 'tostring_rgb'错误
This error pops up because the default Matplotlib backend (Agg, which is non-interactive) doesn't support the tostring_rgb method. You already found one fix by switching to the TkAgg backend, but here are a couple more flexible options:
- If you just need to display the plot interactively:
- First check your current backend with
import matplotlib; print(matplotlib.get_backend()) - Make sure your environment has a supported GUI backend installed (like Tkinter, Qt5Agg, etc.). If not, you can install the required dependencies (e.g.,
python3-tkon Linux, or Tkinter for Windows/macOS)
- First check your current backend with
- If you don't need an interactive window and just want to save the plot:
- Replace
plt.show()withplt.savefig('monthly_money.png')— this works perfectly with the default Agg backend and avoids the error entirely.
- Replace
2. 数据处理与绘图识别问题
Looking at your code, there's a tiny issue that might be causing data parsing failures:
When you split the line 1月: 7000 with split(':')[-1], you get a string with leading whitespace (' 7000'). Trying to convert this directly to an integer will throw a ValueError. Fix this by adding .strip() to remove extra spaces:
money = newContent.split(':')[-1].strip()
Also, your plt.legend() won't show anything right now because you haven't added a label to your plot line. Update the plot line to include a label so the legend makes sense:
plt.plot(x, y, 'r', label='Monthly Income')
3. 验证Matplotlib安装路径
To check if Matplotlib is installed in your current Python environment:
- Run these lines in your Python interpreter:
import matplotlib import sys print("Matplotlib path:", matplotlib.__file__) print("Current Python interpreter:", sys.executable) - If the paths don't match, it means you installed Matplotlib in a different Python environment. Fix this by:
- Using your current Python's pip to reinstall: run
python3 -m pip install --upgrade matplotlib(replacepython3with your actual Python command, likepythonorpy -3) - If you're using a virtual environment, make sure you activate it first before running the install command.
- Using your current Python's pip to reinstall: run
修正后的完整代码
Here's your code with all the fixes applied:
import matplotlib.pyplot as plt # 读取并处理数据 with open('notebook.txt', encoding='utf-8') as file: contents = file.readlines() newList = [] for content in contents: newContent = content.strip() # 一次性去掉换行和前后空格 if newContent: # 跳过可能存在的空行 money = newContent.split(':')[-1].strip() newList.append(int(money)) print(newList) # 绘图 x = [1, 2, 3, 4, 5, 6] y = newList plt.plot(x, y, 'r', label='Monthly Income') plt.xlabel('Month') plt.ylabel('Money') plt.legend() plt.show()
备注:内容来源于stack exchange,提问作者algh404

