python绘图设置纵坐标保留两位小数
时间: 2025-06-25 13:16:03 浏览: 12
### 设置 Matplotlib Y 轴刻度格式为两位小数
在 Python 的 Matplotlib 库中,可以通过 `FuncFormatter` 来自定义坐标轴的刻度显示格式。具体来说,可以利用字符串格式化方法来指定数值的小数位数。
以下是实现此功能的一个完整示例:
```python
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
# 创建一些数据用于绘图
data = [1.2345, 2.3456, 3.4567, 4.5678]
fig, ax = plt.subplots(figsize=(10, 5))
# 绘制折线图
ax.plot(data, color='blue')
# 定义一个函数来自定义Y轴刻度格式
def two_decimal_places(x, pos):
"""Format the number to show only two decimal places."""
return "{:.2f}".format(x)
# 使用 FuncFormatter 将上述函数应用到 Y 轴上
formatter = FuncFormatter(two_decimal_places)
ax.yaxis.set_major_formatter(formatter)
plt.show()
```
在这个例子中,我们创建了一个名为 `two_decimal_places` 的函数[^3],该函数接受两个参数:一个是当前的刻度值 (`x`),另一个是位置信息 (`pos`)。这个函数返回经过格式化的字符串,其中保留了两位小数。接着我们将这个函数传递给 `FuncFormatter` 并将其应用于 Y 轴的主要刻度标签。
#### 关于 Pandas DataFrame 切片操作
如果需要处理的是 Pandas 数据框中的子集,则可采用如下方式获取特定范围的数据并绘制图表:
```python
df.iloc[3:5, 0:2].plot(subplots=False, figsize=(10, 5), color='blue')
plt.gca().yaxis.set_major_formatter(FuncFormatter(lambda x, _: f"{x:.2f}"))
plt.show()
```
这里同样调用了 `set_major_formatter` 方法以确保纵坐标的精度保持一致[^2]。
阅读全文
相关推荐

















