Để vẽ Biểu đồ thanh ngang, hãy sử dụng pandas.DataFrame.plot.barh . Biểu đồ thanh hiển thị so sánh giữa các danh mục rời rạc.
Đầu tiên, hãy nhập các thư viện được yêu cầu -
import pandas as pd import matplotlib.pyplot as plt
Tạo một Pandas DataFrame có 4 cột -
dataFrame = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 110, 150, 80, 200, 90]
}) Vẽ biểu đồ thanh ngang bằng cách sử dụng plot.barh () -
dataFrame.plot.barh(x='Car', y='Cubic_Capacity', title='Car Specifications', color='blue')
Ví dụ
Sau đây là mã hoàn chỉnh -
import pandas as pd
import matplotlib.pyplot as plt
# creating dataframe
dataFrame = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'BMW', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000],"Units_Sold": [ 100, 110, 150, 80, 200, 90]
})
# plotting Horizontal Bar Chart
dataFrame.plot.barh(x='Car', y='Cubic_Capacity', title='Car Specifications', color='blue')
# set the label
plt.xlabel("CC (Cubic Capacity)" )
# display the plotted Horizontal Bar Chart
plt.show() Đầu ra
Điều này sẽ tạo ra kết quả sau -