这是我仅使用 matplotlib 和 numpy 的答案。
与接受的答案相比,我的代码似乎很长。因此,如果有人可以帮助我改进它,那就太好了!
代码在这里:
## Reading the data
year = np.arange(1994,2015,1)
type = ["Recalled", "Recovered"]
value_1 = [11.472, 11.81, 10.632, 13.857, 13.861, 13.375, 11.278, 12.827, 12.687, 10.859, np.nan, 11.782, 12.089,\
14.351, 14.921, 11.759, 12.987, 13.262, 9.98, 10.626, 12.199]
value_2 = [10.207, 10.326, 10.094, 12.944, 12.588, 11.951, np.nan, np.nan, np.nan, np.nan, np.nan, 11.047, 10.194,\
13.401, 13.886, 10.815, 11.482, 10.73, 9.52, 9.591, 10.27]
## Changing data into ndarray format
dpoints = np.array([type[0], year[0], value_1[0]])
conditions = np.unique(dpoints[:,0])
categories = np.unique(dpoints[:,1]).tolist()
for i in range(1,len(year),1):
dpoints = np.vstack([dpoints,np.array([type[0],year[i],value_1[i]])])
for i in range(0,len(year),1):
dpoints = np.vstack([dpoints,np.array([type[1],year[i],value_2[i]])])
# Plot it!
fig = plt.figure(figsize=(16,5))
ax = plt.subplot()
#the space between each set of bars
space = 0.2
n = len(conditions)
width = (1 - space) / (len(conditions))
# Create a set of bars at each position
for i,cond in enumerate(conditions):
indeces = range(1, len(categories)+1)
vals = dpoints[dpoints[:,0] == cond][:,2].astype(np.float)
pos = [j - (1 - space) / 2. + i * width for j in indeces]
ax.bar(pos, vals, width=width, label =cond,lw = 0,color= ["blue","r"][i],alpha = 0.6)
# Set the x-axis tick labels to be equal to the categories
ax.set_xticks(indeces)
ax.set_xticklabels(categories)
ax.set_xlim(0,22)
plt.setp(plt.xticks()[1], rotation=0,fontsize = 12)
ax.set_ylabel('Variables',fontsize =15)
ax.set_xlabel("Year",fontsize =15)
# Add a legend
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[::-1], labels[::-1], loc='upper left',frameon =False,fontsize =12)
图在这里