多索引DataFrame绘图报错:无法使用m04hour.index的问题求助
Hey there, let's get this sorted out! The error you're hitting happens because matplotlib's ax.plot() doesn't know how to handle a multi-index directly, while pandas' built-in plot() method is designed to automatically handle multi-index structures behind the scenes.
Why the Error Occurs
When you call m04hour['consumption (kWh)'].plot(), pandas takes care of translating the multi-index into a readable x-axis for you. But when you pass m04hour.index directly to ax.plot(), matplotlib sees a nested sequence (the multiple levels of your index) and throws that ValueError because it expects a single, flat sequence for the x-axis.
Solutions to Try
1. Use Pandas' Plot with Your Matplotlib Axes (Simplest Fix)
Keep using pandas' smart plot handling, but attach it to your pre-defined matplotlib axes. This way you get the best of both worlds:
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(8,4)) # Pass your ax object to pandas' plot method m04hour['consumption (kWh)'].plot(ax=ax, color='red', linewidth=1, label='queens') ax.legend() plt.tight_layout() plt.show()
2. Extract a Single Level from the Multi-Index
If you specifically want to use one level of your multi-index as the x-axis, use get_level_values() to pull out that flat sequence:
import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(8,4)) # Replace 0 with the index level you want (e.g., 1 for the second level) x_axis = m04hour.index.get_level_values(0) ax.plot(x_axis, m04hour['consumption (kWh)'], c='red', lw=1, label='queens') ax.legend() # Rotate ticks if needed for readability plt.xticks(rotation=45) plt.tight_layout() plt.show()
3. Combine Multi-Index Levels into a Single Value (e.g., Datetime)
If your multi-index is time-based (like date + hour), merge the levels into a single datetime index that matplotlib can easily interpret:
import matplotlib.pyplot as plt import pandas as pd # Merge index levels into a datetime column m04hour['timestamp'] = pd.to_datetime( m04hour.index.get_level_values(0).astype(str) + ' ' + m04hour.index.get_level_values(1).astype(str) ) fig, ax = plt.subplots(figsize=(8,4)) ax.plot(m04hour['timestamp'], m04hour['consumption (kWh)'], c='red', lw=1, label='queens') ax.legend() plt.xticks(rotation=45) plt.tight_layout() plt.show()
Any of these approaches should resolve that ValueError and let you plot your data correctly with matplotlib.
内容的提问来源于stack exchange,提问作者Giles Richardson

