r/learnpython • • 1d ago

matplotlib graphs from csv file

hi! i dont rly use reddit but i need some help. does anyone know how to make matplotlib graphs from a csv file? i can do the basics but i cant seem to figure out this dataset, and i need to submit my project soon. any and all help is appreciated

3 Upvotes

7 comments sorted by

View all comments

1

u/chingisooinar 6h ago

If pandas is allowed, this skeleton covers most csv plots:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv("data.csv")
print(df.head())      # check column names and types first
print(df.dtypes)

fig, ax = plt.subplots()
ax.plot(df["x_column"], df["y_column"])   # or ax.bar / ax.scatter
ax.set_xlabel("x label")
ax.set_ylabel("y label")
ax.set_title("title")
plt.tight_layout()
plt.savefig("plot.png")
plt.show()

If you need totals per category, do df.groupby("category")["value"].sum().plot(kind="bar"). The usual reasons a dataset "won't work" are numbers being read as strings (commas or units in them) or dates not parsed, so use pd.to_numeric(..., errors="coerce") or pd.read_csv(..., parse_dates=["date"]). If you paste the output of df.head() I can help with the exact plot.