Pandas时序数据折线与散点组合绘图及问题解决
Solution: Plot Time Series Line + Scatter Points (No Lines) in Pandas
Got it, let's fix this step by step! The key issues you're facing are:
- Preventing lines from connecting your scatter points
- Ensuring the legend properly displays for those points
Here's a complete, working example that addresses both problems:
Step 1: Set Up Libraries & Sample Data
First, let's replicate your data structure so you can test this directly:
import pandas as pd import matplotlib.pyplot as plt # Create a year of daily time series data daily_dates = pd.date_range(start="2015-01-01", end="2015-12-31", freq="D") df_daily = pd.DataFrame( {"daily_values": pd.np.random.randn(len(daily_dates)).cumsum()}, index=daily_dates ) # Your specific points data (matches your example) df_points = pd.Series( [34.0, 86.914286, 55.7], index=pd.to_datetime(["2015-10-31", "2015-11-30", "2015-12-20"]), name="point_values" )
Step 2: Plot the Line + Scatter Points
The trick is to explicitly turn off the line for the scatter points using linestyle='none', and set a clear label for the legend:
# First, plot the daily line chart ax = df_daily.plot( kind="line", label="Daily Values", figsize=(10, 6), color="blue" ) # Now plot the scatter points WITHOUT connecting lines df_points.plot( ax=ax, # Use the same axis as the line chart marker="o", # Choose your marker type (e.g., 'x', 's', '^') linestyle="none", # This removes the line between points color="red", markersize=8, # Adjust marker size if needed label="Specific Points" # Ensures legend entry shows up ) # Add labels and title for clarity plt.xlabel("Date") plt.ylabel("Value") plt.title("Daily Time Series + Specific Scatter Points") plt.legend() plt.show()
Why This Works
linestyle='none'is the critical parameter here: it tells Pandas/Matplotlib to only draw markers, not a connecting line.- Using
label="Specific Points"ensures the legend entry appears correctly (this was likely missing when you usedstyle='x'). - If you prefer a different marker (like 'x'), just replace
marker="o"withmarker="x".
Alternative: Use Matplotlib's Scatter Directly
If you want more control, you can use Matplotlib's native scatter method instead:
ax = df_daily.plot(kind="line", label="Daily Values", figsize=(10,6)) ax.scatter(df_points.index, df_points.values, marker="x", color="green", label="Specific Points") plt.legend() plt.show()
This achieves the exact same result—no lines between scatter points, and a proper legend.
内容的提问来源于stack exchange,提问作者Fab
相关产品推荐
相关产品推荐

