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

Shiny Express应用柱状图Y轴无法设为0的问题求助

问题原因

set_ylim设置未生效的核心问题是数据类型错误:当你把字符串类型的Maturity和数值类型的Yield合并为同一个numpy数组时,numpy会将所有元素统一转换为字符串类型。此时y = data[1]得到的是字符串数组而非数值数组,导致matplotlib无法正确识别数值范围,进而忽略set_ylim的配置。

修复方案

方案1:使用Pandas DataFrame(推荐)

Pandas可以保留不同列的原生数据类型,避免类型强制统一的问题:

from shiny.express import input, render, ui
import matplotlib.pyplot as plt
import pandas as pd

data = {
    "Maturity": ['1Y', '2Y', '3Y', '4Y', '5Y', '6Y', '7Y', '8Y'],
    "Yield": [4.1, 4.3, 4.5, 4.7, 4.8, 4.9, 5.0, 5.1]
}
df = pd.DataFrame(data)

def create_line_plot():
    x = df["Maturity"]
    y = df["Yield"]  # 保持数值类型
    fig, ax = plt.subplots()
    ax.bar(x, y)
    ax.set_xlabel("Maturity")
    ax.set_ylabel("Yield (%)")
    ax.set_ylim(bottom=0)  # 设置正常生效
    return fig

@render.plot
def my_plot():
    return create_line_plot()

方案2:手动转换Yield为数值类型

如果不想依赖Pandas,可单独存储数据并明确指定数值类型:

from shiny.express import input, render, ui
import matplotlib.pyplot as plt
import numpy as np

data = {
    "Maturity": ['1Y', '2Y', '3Y', '4Y', '5Y', '6Y', '7Y', '8Y'],
    "Yield": [4.1, 4.3, 4.5, 4.7, 4.8, 4.9, 5.0, 5.1]
}
# 分开存储两类数据,避免类型统一
maturity = np.array(data["Maturity"])
yield_vals = np.array(data["Yield"], dtype=np.float64)  # 强制指定数值类型

def create_line_plot():
    x = maturity
    y = yield_vals
    fig, ax = plt.subplots()
    ax.bar(x, y)
    ax.set_xlabel("Maturity")
    ax.set_ylabel("Yield (%)")
    ax.set_ylim(bottom=0)
    return fig

@render.plot
def my_plot():
    return create_line_plot()
效果验证

修复后,柱状图的Y轴会从0开始,set_ylim的配置正常生效,能直观展示收益率的数值对比。

内容的提问来源于stack exchange,提问作者Tommie Jones

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.12 22:42:38