How can I draw a matplotlib histogram in python shiny?

63 Views Asked by At

I am new to both Python and Shiny and I am having trouble drawing a histogram using matplotlib in Python Shiny.

This is my app:

from shiny import App, ui, reactive, render
import numpy as np
import matplotlib.pyplot as plt

app_ui = ui.page_fluid(
    ui.panel_title("My Shiny Test Application"),
    ui.layout_sidebar(
      ui.panel_sidebar(
        ui.input_slider(
          "nr_of_observations", 
          "Number of observations",
          min = 0,
          max = 100,
          value = 30
        )
      ),
      ui.panel_main(
        ui.navset_tab(
          ui.nav(
            "Scatter",
            ui.output_plot("my_scatter")
          ),
          ui.nav(
            "Histogram",
            ui.output_plot("my_histogram")
          ),
          ui.nav(
            "Summary",
            ui.output_text_verbatim("my_summary"),
          )
        )
      )
    )
  )


def server(input, output, session):
  @reactive.Calc
  def random_data():
    return np.random.rand(input.nr_of_observations())
  
  @output
  @render.plot
  def my_scatter():
    return plt.scatter(random_data(), random_data())
  
  @output
  @render.plot
  def my_histogram():
    return plt.hist(random_data())

  @output
  @render.text
  def my_summary():
    return(random_data())
  
app = App(app_ui, server)

The scatter plot works, but for the histogram I am getting an error, which I don't understand.

In a script, everything works fine:

import matplotlib.pyplot as plt
import numpy as np
random_numbers = np.random.rand(20)
plt.scatter(random_numbers, random_numbers)
plt.show()

plt.close()
plt.hist(random_numbers)
plt.show()

Can anyone help me to understand the problem and give a hint to solve it?

Thanks in advance and best greetings, Sebastian

1

There are 1 best solutions below

0
Sebastian Gerdes On

I found two options, how I can make it work: Option 1:

  @render.plot
  def my_histogram():
    plt.hist(random_data())

Option 2:

@output
  @render.plot
  def my_histogram():
    return plt.hist(random_data())[2]2

Even more information can be found in the shiny for python documentation: Link