In my application I generate plots using pandasai. Those plots shall only be saved locally and NOT be opened in an external window. How to do this? It always opens the plot also in an external window. I already set
matplotlib.use('Agg')
and configured
sdf = SmartDataframe(df, config={
"llm": llm,
"save_charts": True,
"save_charts_path": temp_dir,
})
to avoid that behaviour. Neither of that worked. It saves the image locally but also opens an external window for the plot. The code generated from pandasai looks like this:
df = dfs[0]
department_counts = df['Department'].value_counts()
plt.figure(figsize=(8, 8))
department_counts.plot.pie(autopct='%1.1f%%', startangle=140)
plt.title('Employees by Department')
plt.ylabel('')
chart_filename = 'xxx/temp_chart.png'
plt.savefig(chart_filename)
result = {'type': 'plot', 'value': chart_filename}
When I execute this. No external window of the saved PNG-file opens.
My full code for clarification:
from pandasai import SmartDataframe
from pandasai.llm import AzureOpenAI
import os, base64
import pandas as pd
import matplotlib, tempfile
matplotlib.use('Agg')
def generate_plot():
api_token = os.getenv("AZURE_OPENAI_API_KEY")
azure_endpoint = "xxx"
api_version="2024-02-15-preview"
deployment_name="xxx"
llm = AzureOpenAI(
api_token=api_token,
azure_endpoint=azure_endpoint,
api_version=api_version,
deployment_name=deployment_name
)
fp = 'xxx'
df = pd.read_excel(fp)
with tempfile.TemporaryDirectory() as temp_dir:
# Convert to SmartDataframe
sdf = SmartDataframe(df, config={
"llm": llm,
"save_charts": True,
"save_charts_path": temp_dir,
})
sdf.chat("Visualize employees by department in a pie chart.")
file_list = os.listdir(temp_dir)
file_path = os.path.join(temp_dir, file_list[0])
with open(file_path, 'rb') as img:
return base64.b64encode(img.read()).decode('utf-8')
img_base64 = generate_plot()
4