Python Pandas - 建立一個水平條形圖
要繪製水平條形圖,請使用 pandas.DataFrame.plot.barh。條形圖顯示離散類別之間的比較。
首先,匯入必要的庫 -
import pandas as pd import matplotlib.pyplot as plt
使用 4 列建立 Pandas 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] })
使用 plot.barh() 繪製水平條形圖 -
dataFrame.plot.barh(x='Car', y='Cubic_Capacity', title='Car Specifications', color='blue')
示例
以下為完整程式碼 -
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()
輸出
將生成以下輸出 -
廣告