[英]How do i plot a pandas.DataFrame.plot.bar() with this weird columns in my pandas dataframe?
我目前有這個數據框,看起來像這樣:
目前,我正在嘗試繪制以這種方式分組的條形圖:
下面是我試圖用來繪制條形圖的代碼:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# import the csv file
dataname = 'Datasets\\filing-of-tax-returns-for-individual-income-tax-and-corporate-income-tax.csv'
data = pd.read_csv(dataname,na_values=['na'])
df = pd.DataFrame(data)
# drop the NaN values
df2 = df.dropna()
# drop the rows that include values for individual income tax as it is irrelevent
df2 = df2[df2.tax_type != 'Individual Income Tax']
df2
# drop the column tax_type as we alr filter out to be a corporate income tax
df3 = df2.drop(columns = 'tax_type')
df3
# draw the bar chart to see the respectiive return_type for each respective year
df3.plot.bar(x='year_of_assessment',rot=0,figsize=(40,20))
plt.show()
免責聲明:我被告知不要使用 matplotlib 繪制圖形。
您可以使用 Pandas 的plot()
繪制此圖表,只需在繪制之前重新排列Pandas 中的數據即可。
只需對您的數據進行透視,使評估年份成為索引,返回類型成為列。
您可以通過簡單的操作來做到這一點:
df4 = df3.pivot_table(
index=['year_of_assessment'],
columns=['return_type'],
)
在這一點上,一個簡單的df4.plot.bar()
會做你想做的。
您可以通過調整軸、圖例和標題的標簽使其稍微好一點,但此時主要是外觀調整:
ax = df4.plot.bar()
ax.legend(labels=df4.columns.levels[1])
ax.set_xlabel('Year of Assessment')
ax.set_title('Returns Received On Time')
plt.show()
這是我得到的一個示例圖,其中包含一小部分數據,看起來像您共享的數據:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.