【发布时间】:2020-08-31 19:08:35
【问题描述】:
file_path 是一个 excel 文件,其中“年份”列包含 1940 到 2018 年的数字,另一列“1976 年除法”表示 1976 年之前或 1976 年至今。
# Load excel file as a pandas data_frame
data = pd.read_excel(file_path, sheet_name=5, skiprows=1)
data_frame = pd.DataFrame(data)
# create an extra column in data_frame with bin from 1930 to 2020 with 10 years interval
data_frame['bin Year'] = pd.cut(data_frame.Year, bins=np.arange(1930, 2030, 10, dtype=int))
# Plot stacked bar plot
color_table = pd.crosstab(index=data_frame['bin Year'], columns=data_frame['Divide Year 1976'])
color_table.plot(kind='bar', figsize=(6.5, 3.5), stacked=True, legend=None, edgecolor='black')
# Add xticks
plt.xticks(locs, ['1930s','1940s','1950s','1960s','1970s','1980s','1990s','2000s','2010s'], fontsize=8, rotation=45)
这里的问题是 colortable.plot() 函数会自动忽略计数为 0 的区间,在我的例子中是 1940-1950。如何强制代码显示在特定间隔内计数为零的条形?
【问题讨论】:
标签: python pandas dataframe bar-chart histogram