熊猫交叉表绘图未显示间隔为零的间隔

问题描述

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。如何强制代码显示在特定间隔内计数为零的条形?

enter image description here

解决方法

在交叉表中使用参数Cannot convert value of type 'ButtonTextModifier.Content' (aka '_ViewModifier_Content<ButtonTextModifier>') to type 'Text' in coercion

dropna

请参见docs