在Pandas中绘制多层索引DataFrame:按symbol分线同图展示
Got it, let's walk through how to plot each symbol as a distinct line on the same chart, assuming your multi-index DataFrame uses something like (date/time, symbol) as its index (super common for time-series data with multiple assets). I'll cover two straightforward methods, plus some tips for customization.
First, Let's Set Up a Sample DataFrame (to match your structure)
If you don't already have one, here's a quick example to work with—this mimics the kind of data you're describing:
import pandas as pd import numpy as np import matplotlib.pyplot as plt # Create sample multi-index data dates = pd.date_range('2024-01-01', periods=15) symbols = ['AAPL', 'MSFT', 'GOOGL'] multi_idx = pd.MultiIndex.from_product([dates, symbols], names=['date', 'symbol']) # Generate cumulative random values to simulate trends values = np.random.randn(45).cumsum() df = pd.DataFrame({'value': values}, index=multi_idx)
Method 1: Unstack the Symbol Index (Simplest Approach)
The easiest way is to "unstack" the symbol level from your index into columns. Pandas' built-in plot() will automatically draw a line for each column:
# Unstack the 'symbol' index level to turn it into columns df_unstacked = df.unstack(level='symbol') # Clean up the column names (unstack creates a multi-level column by default) df_unstacked.columns = df_unstacked.columns.droplevel(0) # Plot all symbols on the same chart df_unstacked.plot(figsize=(10, 6), linewidth=2) plt.title('Symbol Value Trends Over Time') plt.xlabel('Date') plt.ylabel('Value') plt.legend(title='Ticker Symbol') plt.grid(alpha=0.3) plt.show()
This works because unstacking transforms your data into a wide format where each symbol is a separate column—exactly what Pandas needs to plot individual lines.
Method 2: Group by Symbol (More Flexible for Customization)
If you want more control over each line's style (colors, markers, etc.), use groupby() to iterate over each symbol and plot manually:
plt.figure(figsize=(10, 6)) # Group the DataFrame by the 'symbol' index level for symbol, group_data in df.groupby(level='symbol'): # Drop the symbol index level so we can use date as the x-axis group_data = group_data.reset_index(level='symbol', drop=True) # Plot with custom styling (adjust as needed) group_data.plot( label=symbol, linewidth=2, marker='o', markersize=4, legend=True ) plt.title('Customized Symbol Value Trends') plt.xlabel('Date') plt.ylabel('Value') plt.legend(title='Ticker Symbol') plt.grid(alpha=0.3) plt.show()
This method lets you tweak each line individually—great if you want to highlight specific symbols with unique colors or markers.
Quick Tips
- If your
symbolis in a different index level (e.g., first instead of second), adjust thelevelparameter inunstack()orgroupby()(uselevel=0instead oflevel='symbol'). - If your DataFrame has multiple value columns, specify which one to plot:
df_unstacked['your_value_column'].plot(). - Use Pandas' plot styling options (like
color,linestyle,marker) to make your chart easier to read.
内容的提问来源于stack exchange,提问作者Evan Kim

