如何在Matplotlib中将排序后的datetime对象列表绘制成折线图
Alright, let's get your sorted datetime list plotted as a line chart in Matplotlib. I'll cover two common use cases since your list has duplicate dates: plotting the sequence of entries, and plotting the count of each unique date. Here's how to do both:
First, make sure you have the necessary tools imported:
import matplotlib.pyplot as plt from datetime import date
Let's use your sample truncated list for the examples:
X = [date(2017, 1, 14), date(2017, 1, 14), date(2017, 1, 16), date(2017, 1, 16), date(2017, 1, 18), date(2017, 1, 22), date(2017, 1, 24), date(2017, 1, 24), date(2017, 1, 29), date(2017, 2, 4)]
If you want to visualize the order of dates (with each entry in X as a point on the line), use the index of each element as the y-value:
# Create y-values as the position of each date in the list y = list(range(len(X))) # Generate the plot plt.figure(figsize=(10, 6)) plt.plot(X, y, marker='o', linestyle='-', color='#1f77b4') # Format the axis for readability plt.xlabel('Date', fontsize=12) plt.ylabel('Sequence Position', fontsize=12) plt.title('Sequence of Dates in List', fontsize=14) plt.xticks(rotation=45) # Rotate labels to avoid overlap plt.tight_layout() # Adjust layout to fit rotated text plt.show()
This produces a line that increments with each entry in your list, with markers for every date instance.
Since your list has duplicate dates, you might want to show how many times each date appears. Use collections.Counter to tally occurrences first:
from collections import Counter # Count how many times each date appears date_counts = Counter(X) # Extract sorted unique dates and their corresponding counts unique_dates = sorted(date_counts.keys()) count_values = [date_counts[date] for date in unique_dates] # Generate the count plot plt.figure(figsize=(10, 6)) plt.plot(unique_dates, count_values, marker='s', linestyle='-', color='#2ca02c') # Format the axis plt.xlabel('Date', fontsize=12) plt.ylabel('Number of Occurrences', fontsize=12) plt.title('Frequency of Each Date', fontsize=14) plt.xticks(rotation=45) plt.tight_layout() plt.show()
This line chart will highlight which dates repeat and how often.
For better control over x-axis date labels (like custom formats or interval ticks), use matplotlib.dates:
import matplotlib.dates as mdates # After plotting, add these lines to format the x-axis plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) # Show a tick every 7 days (adjust interval as needed) plt.gca().xaxis.set_major_locator(mdates.DayLocator(interval=7))
This ensures dates are displayed in a clean YYYY-MM-DD format and prevents tick clutter for long date lists.
内容的提问来源于stack exchange,提问作者Prateek Dewan

