You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pandas结合Pyplot绘图遇问题:Y轴刻度异常及yerr报错

Hey there! Let's tackle your two Pandas + Matplotlib issues one by one:

Issue 1: Y-axis ticks are out of order (10 appears before 1)

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.

Issue 2: TypeError when using the 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:25:04