![]() |
|
[Tut] [Fixed] Matplotlib: TypeError: ‘AxesSubplot’ object is not subscriptable - Printable Version +- Sick Gaming (https://sickgaming.net) +-- Forum: Programming (https://sickgaming.net/forum-76.html) +--- Forum: Python (https://sickgaming.net/forum-83.html) +--- Thread: [Tut] [Fixed] Matplotlib: TypeError: ‘AxesSubplot’ object is not subscriptable (/thread-99906.html) |
[Tut] [Fixed] Matplotlib: TypeError: ‘AxesSubplot’ object is not subscriptable - xSicKxBot - 09-05-2022 [Fixed] Matplotlib: TypeError: ‘AxesSubplot’ object is not subscriptable 5/5 – (1 vote) Problem Formulation Say, you’re me five minutes ago, and you want to create a Matplotlib plot using the following (genius) code snippet:Code: import matplotlib.pyplot as plt fig, axes = plt.subplots()
axes[0, 0].plot([1, 2, 3], [9, 8, 7])
plt.show()If you run this code, instead of the desired plot, you get the following Code: TypeError: 'AxesSubplot' object is not subscriptableCode: Traceback (most recent call last): File "C:\Users\xcent\Desktop\code.py", line 4, in <module> axes[0, 0].plot([1, 2, 3], [5, 5, 5])
TypeError: 'AxesSubplot' object is not subscriptable Question: How to resolve the Code: TypeError: 'AxesSubplot' object is not subscriptableDon’t panic! The solution is easier than you think…Fix Not Subscriptable TypeError on ‘AxesSubplot’ Object Generally, Python raises the Code: TypeError XXX object is not subscriptableCode: AxesCode: AxesLet’s go over the code to understand why the error happened! First, you assign the result of the Code: plt.subplots()Code: figCode: axesCode: fig, axes = plt.subplots()If you don’t pass an argument in the Code: plt.subplots()Code: FigureCode: AxesSo if you try to subscript using Code: axes[0,0]Code: axes[0]Code: axesSo to fix the Code: TypeError: 'AxesSubplot' object is not subscriptableCode: plt.subplots()Code: import matplotlib.pyplot as plt fig, axes = plt.subplots()
axes.plot([1, 2, 3], [9, 8, 7]) # not: axes[0, 0]
plt.show()Now it works — here’s the output: ![]() What is the Reason for the Error? However, this error is tough to spot because if you pass any other argument into the Code: plt.subplot()Code: FigureCode: SubplotCode: AxesCode: figCode: axesFor example, this creates a non-subscriptable axes because you don’t pass any argument: Code: fig, axes = plt.subplots()For example, this creates a subscriptable array of axes that is a one-dimensional array of subplots because you pass an argument: Code: fig, axes = plt.subplots(3)For example, this creates a subscriptable array of axes that is a two-dimensional array of subplots because you passed two arguments Code: fig, axes = plt.subplots(3, 2)No wonder did you think that you can call Code: axes[0,0]Code: axes[0]Code: plt.subplot()Make sure you never run into similar errors by spending a couple of minutes understanding the Code: plt.subplot()Learn More about plt.subplot() To further understand the Code: subplots() Full Tutorial: Matplotlib Subplots – A Helpful Illustrated Guide
|