How to Force PandasAI to Use Plotly Instead of Matplotlib for Visualizations #1818
Replies: 2 comments
-
|
Hi! It does not work with LiteLLM (didn't investigate why - probably different use of custom prompt), but with OpenAI I use the following in the agent prompt. "When plotting - use appropriate Plotly chart, write plot to image file and return path. Display the plot using Streamlit (import streamlit as st; st.plotly_chart) if returning chart response. Do not run .show() on figure. Use pio.write_image to save image to file." |
Beta Was this translation helpful? Give feedback.
-
|
Good question! PandasAI defaults to matplotlib, but you can steer it toward Plotly. Solution 1: Custom instructions from pandasai import Agent
agent = Agent(
dfs=[df],
config={
"custom_instructions": """
ALWAYS use Plotly for visualizations, never matplotlib.
Use plotly.express (px) for simple charts.
Use plotly.graph_objects (go) for complex visualizations.
Return fig.to_html() for Streamlit compatibility.
"""
}
)Solution 2: Prompt the query directly response = agent.chat(
"Create a bar chart of sales by region using Plotly"
)Solution 3: Custom skills from pandasai.skills import skill
@skill
def plot_chart(df, chart_type: str, x: str, y: str):
"""
Create interactive Plotly charts.
Use this for ALL visualization requests.
"""
import plotly.express as px
chart_funcs = {
"bar": px.bar,
"line": px.line,
"scatter": px.scatter,
"pie": px.pie,
}
fig = chart_funcs[chart_type](df, x=x, y=y)
return fig.to_html()
agent = Agent(dfs=[df], skills=[plot_chart])For Streamlit specifically: import streamlit as st
response = agent.chat("Plot sales trend with Plotly")
if "<div" in str(response): # HTML output
st.components.v1.html(response, height=500)We build Streamlit + PandasAI dashboards at Revolution AI — the custom skills approach gives the most reliable Plotly output. |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I've been experimenting with PandasAI and noticed that whenever I query to generate a plot (e.g., scatter, pie, bar), the logs show that it defaults to generating visualization code using Matplotlib behind the scenes.
For my use case, especially involving interactive dashboards with streamlit, I’d prefer the llm to generate Plotly code instead.
Is there a way to:
Any tips, config flags, or examples would be greatly appreciated.
Beta Was this translation helpful? Give feedback.
All reactions