使用Pandas结合Pyplot绘图遇问题:Y轴刻度异常及yerr报错
Hey there! Let's tackle your two Pandas + Matplotlib issues one by one:
Root Cause
This almost always happens because your Y-axis data (and likely other related columns) are stored as string types instead of numeric types. When Matplotlib plots string values, it sorts them lexicographically (like dictionary order) rather than numerically. For example, '10' gets placed before '1' in string sorting because the second character '0' is treated as "smaller" than having no second character.
Fix
Convert your relevant DataFrame columns to numeric types using pd.to_numeric(). You can do this for the entire DataFrame (if all columns should be numeric) or target specific columns:
# Convert all columns to numeric (coerces non-numeric values to NaN if needed) df = df.apply(pd.to_numeric, errors='coerce') # Or convert specific columns (e.g., Y-axis column and error column) df.iloc[:, 1] = pd.to_numeric(df.iloc[:, 1], errors='coerce') df['your_error_column'] = pd.to_numeric(df['your_error_column'], errors='coerce')
After conversion, Matplotlib will recognize the values as numbers and display them in the correct numeric order on the Y-axis.
yerr parameter Root Cause
Same core issue as the first problem! The yerr argument requires numeric values to calculate error bar ranges, but you're passing string data. When Matplotlib tries to compute ranges like y - yerr, it can't perform subtraction on strings, hence the error.
Fix
First, convert the column used for yerr to a numeric type (using the same pd.to_numeric() method above). Then adjust your errorbar call to pass 1D arrays instead of DataFrame slices (since df.iloc[:, n:n+1] returns a DataFrame, not a Series/array):
# After converting columns to numeric ax.errorbar( x=df.iloc[:, 0].values, # Extract 1D array for x-values y=df.iloc[:, 1].values, # Extract 1D array for y-values yerr=df.iloc[:, 2].values # Replace 2 with your error column's index )
For better readability, you can also use column names directly if your DataFrame has headers:
ax.errorbar( x=df['x_column_name'], y=df['y_column_name'], yerr=df['error_column_name'] )
Quick Pro Tip
You can avoid this type issue entirely when loading your data by specifying data types upfront in pd.read_table():
# Define data types for each column (adjust indices/names to match your data) dtype_map = {0: float, 1: float, 2: float} df = pd.read_table('TI_attachment.dat', header=0, sep='\s+', dtype=dtype_map)
This way, Pandas parses the columns as numeric types right when loading the file, skipping the post-processing conversion step.
内容的提问来源于stack exchange,提问作者ta8

