How to display text and plotly chart with gradio in the same output box

151 Views Asked by At

I have a code which is a chatgpt agent answering questions about our database (text to SQL basically). The code works perfectly on its own. However I need to demo it to my management so I need to have some kind of front end to it.

As front end programming it is not my area, I thought I will go with something easy. I thought gradio will do the job, so it is my first gradio app. It works nicely however I run into a problem. The chatbot I created is able to display the text replies however the user can ask for visualization of the results. When asked to visualize the chatbot agent uses plotly.

My problem is that the output text box I am using with gradio cannot display the visualization, only the text. So my question is that, does gradio have an output item which can display text and visualization as well?

Here is my gradio code:

demo=gr.Interface(fn=generate_reply, inputs='text', outputs='text')
demo.launch()
1

There are 1 best solutions below

1
On

To display text and a Plotly chart in the same Gradio output box, follow these steps:

  1. Import Gradio and Plotly:

    import gradio as gr
    import plotly.express as px
    
  2. Create Plotly Chart:

    chart_data = px.data.iris()
    fig = px.scatter(chart_data, x='sepal_width', y='sepal_length', color='species')
    
  3. Combine Text and Chart:

    output_text = "This is a Plotly Chart:"
    output_chart = gr.Image(fig.to_image(format="png"))
    
  4. Define Gradio Interface:

    iface = gr.Interface(fn=lambda: (output_text, output_chart), live=True)
    
  5. Launch Gradio Interface:

    iface.launch()
    

    This code sets up a Gradio interface with both text and the Plotly chart displayed in the same output box for a seamless user experience.