Python中如何将日期时间设为X轴绘制Y值?日期格式报错求助
Fixing ValueError When Parsing Date-Time for Matplotlib Time Series Plot
Let's break down your error and fix it step by step. That ValueError pops up because of two key issues in your date-parsing logic:
- Your input date string uses dots as separators (
2018.05.01) but your format string%Y%m%d%H:%Mexpects no separators for the date part. - Your date and time are stored in separate columns, but you're trying to parse the date column alone with a format that expects both date and time.
Here are two robust solutions to get your time series plot working:
Solution 1: Use Pandas (Recommended for Simplicity)
Pandas handles date-time parsing far more smoothly than raw NumPy for this kind of structured data. Here's how to adjust your code:
import pandas as pd import matplotlib.pyplot as plt import matplotlib.dates as mdates # Define column names to match your data structure column_names = ["date", "time", "open", "high", "low", "close", "volume"] # Load the CSV file with explicit column names df = pd.read_csv("DAT_MT_EURUSD_M1_201805.csv", names=column_names) # Merge date and time columns into a single datetime object df["datetime"] = pd.to_datetime( df["date"] + " " + df["time"], format="%Y.%m.%d %H:%M" # Matches your date-time format exactly ) # Convert datetime objects to Matplotlib-compatible numeric values x_values = mdates.date2num(df["datetime"]) # Plot your data (using closing price as an example) plt.plot(x_values, df["close"]) # Format the X-axis for readability plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y.%m.%d %H:%M")) plt.gcf().autofmt_xdate() # Auto-rotate labels to avoid overlap plt.xlabel("Datetime") plt.ylabel("Price") plt.title("EUR/USD 1-Minute Price Chart") plt.show()
Solution 2: Custom Converter with NumPy
If you prefer sticking with NumPy, you'll need a custom converter function that combines the date and time columns before parsing:
import numpy as np import matplotlib.pyplot as plt import matplotlib.dates as mdates from datetime import datetime def parse_datetime(date_bytes, time_bytes): # Convert byte strings to regular strings and combine datetime_str = f"{date_bytes.decode('utf-8')} {time_bytes.decode('utf-8')}" # Parse into a datetime object dt = datetime.strptime(datetime_str, "%Y.%m.%d %H:%M") # Convert to Matplotlib's numeric date format return mdates.date2num(dt) # Load raw data as byte strings (since we need to process date/time together) raw_data = np.loadtxt( "DAT_MT_EURUSD_M1_201805.csv", delimiter=",", dtype="S20", unpack=False ) # Extract relevant columns dates = raw_data[:, 0] times = raw_data[:, 1] close_prices = raw_data[:, 5].astype(float) # Convert date-time pairs to Matplotlib-compatible values x_values = np.array([parse_datetime(d, t) for d, t in zip(dates, times)]) # Plot the data plt.plot(x_values, close_prices) plt.gca().xaxis.set_major_formatter(mdates.DateFormatter("%Y.%m.%d %H:%M")) plt.gcf().autofmt_xdate() plt.xlabel("Datetime") plt.ylabel("Price") plt.title("EUR/USD 1-Minute Price Chart") plt.show()
Key Takeaways
- Always match your format string to the exact structure of your date-time strings:
%Y.%m.%dforYYYY.MM.DD,%H:%MforHH:MM. - When date and time are split across columns, you must combine them first before parsing into a datetime object.
- Pandas is generally the better choice for time series data due to its built-in date handling tools.
内容的提问来源于stack exchange,提问作者Leonid Chebenko
相关产品推荐
相关产品推荐

