Computer >> Máy Tính >  >> Lập trình >> Python

Python - Cách vẽ biểu đồ dữ liệu gấu trúc trong biểu đồ thanh

Giả sử sau đây là nội dung của tệp CSV của chúng tôi -

       Car   Reg_Price
0      BMW        2000
1    Lexus        1500
2     Audi        1500
3   Jaguar        2000
4  Mustang        1500

Nhập các thư viện bắt buộc -

import pandas as pd
import matplotlib.pyplot as mp

Tệp CSV của chúng tôi ở trên Máy tính để bàn. Tải dữ liệu từ tệp CSV vào Pandas DataFrame -

d = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesData.csv")

dataFrame = pd.DataFrame(d.head(), columns=["Car","Reg_Price"])

Vẽ biểu đồ DataFrame -

dataFrame.plot(x="Car", y="Reg_Price", kind="bar", figsize=(10, 9))

Ví dụ

Sau đây là mã -

import pandas as pd
import matplotlib.pyplot as mp

# read csv
d = pd.read_csv("C:\\Users\\amit_\\Desktop\\SalesData.csv")
print("\nReading the CSV file...\n",d)

# dataframe
dataFrame = pd.DataFrame(d.head(), columns=["Car","Reg_Price"])

# plotting the dataframe
dataFrame.plot(x="Car", y="Reg_Price", kind="bar", figsize=(10, 9))

# displaying bar graph
mp.show()

Đầu ra

Điều này sẽ hiển thị kết quả sau -

Python - Cách vẽ biểu đồ dữ liệu gấu trúc trong biểu đồ thanh