File size: 752 Bytes
69e9d44
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import matplotlib.pyplot as plt
import io
import base64

def df_to_chart(df, chart_type="bar"):
    import pandas as pd
    plt.clf()
    y_col = df.columns[1] if len(df.columns) > 1 else None
    if y_col is not None and pd.api.types.is_numeric_dtype(df[y_col]):
        # Numeric y-column: plot as usual
        ax = df.plot(kind=chart_type, x=df.columns[0], y=y_col, legend=False)
    else:
        # Non-numeric: plot value counts of the first column
        value_counts = df[df.columns[0]].value_counts()
        ax = value_counts.plot(kind="bar")
        ax.set_xlabel(df.columns[0])
        ax.set_ylabel("Count")
    buf = io.BytesIO()
    plt.savefig(buf, format="png")
    buf.seek(0)
    return base64.b64encode(buf.read()).decode("utf-8")