Plot a CSV file in Python
pandas reads the CSV into a DataFrame, and matplotlib draws the chart from its columns. Most of the work is in loading: parsing dates, choosing the right separator and decimal mark, and dropping missing values.
When to use it
- You have a CSV from a spreadsheet, instrument or database export.
- You want a reproducible script instead of a spreadsheet chart.
Watch out: European CSVs often use ; as separator and , as decimal mark. Pass sep=";" and decimal="," to read_csv.
Ask for it in pltchat
Upload your file and type something like:
"plot the value column over the date column, one line per sensor"
pltchat writes the loader and the plot for your columns, runs it in your browser and shows you the code.
The matplotlib code
Self-contained with example data; swap in pd.read_csv(...) or
pd.read_excel(...) for your own file.
import io
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
csv = io.StringIO("""date,sensor,value
2024-03-01,A,20.1
2024-03-01,B,18.4
2024-03-02,A,21.3
2024-03-02,B,19.0
2024-03-03,A,19.8
2024-03-03,B,19.9
2024-03-04,A,22.4
2024-03-04,B,20.6
""")
# Replace csv with your path: pd.read_csv("measurements.csv", parse_dates=["date"])
df = pd.read_csv(csv, parse_dates=["date"]).dropna()
fig, ax = plt.subplots(figsize=(6.4, 4))
for sensor, g in df.groupby("sensor"):
ax.plot(g["date"], g["value"], marker="o", label=f"Sensor {sensor}")
ax.xaxis.set_major_locator(mdates.DayLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%d %b"))
ax.set_ylabel("Temperature (°C)")
ax.legend()
plt.tight_layout()
plt.show()
Upload a CSV, Excel, JSON or Parquet file. Your first plot is always free.