pythonmatplotlibpy-shiny

Why is my Shiny Express app having trouble controlling the barchart plot?


Im having trouble setting the y axis to start at zero for the following shiny express python script. Instead it starts at 4.1 . the set_ylim is having no affect.

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]
}
data=np.array([data["Maturity"], data["Yield"]])
#df = pd.DataFrame(data)
print(data[1])
def create_line_plot():
    x = data[0]
    y = data[1]
    fig, ax = plt.subplots()
    #fig.title("Yield Curve")
    ax.bar(x, y)
    ax.set_xlabel("Maturity")
    ax.yaxis.set_label_text("Yield (%)")
    ax.set_ylim(bottom=0)  # Ensures the y-axis starts at 0 # Ensures the y-axis starts at 0
    return fig

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

Solution

  • This is an issue which results from how you process your data. Avoid the array conversion:

    from shiny.express import render
    import matplotlib.pyplot as plt
    
    data = {
        '1Y': 4.1, '2Y': 4.3, '3Y': 4.5, '4Y': 4.7, 
        '5Y': 4.8, '6Y': 4.9, '7Y': 5.0, '8Y': 5.1
    }
    
    @render.plot
    def create_line_plot():
        x = list(data.keys())
        y = list(data.values())
        fig, ax = plt.subplots()
        ax.bar(x, y)
        ax.set_xlabel("Maturity")
        ax.yaxis.set_label_text("Yield (%)")
        ax.set_ylim(bottom=0)
        return fig
    

    enter image description here