利用python绘制并列的条形图。
(1)处理数据,计算每个区间的个数:
(2)plt.bar函数绘制条形图:
df = pd.read_excel('path of file ',sheet_name='Sheet1')
area_class = df['name']
lake_num = df['lake_number']
TP_lake_num = df['TP_2020_lake_number']
bar_width = 0.3
index_lake = np.arange(len(area_class))
index_TP = index_lake + bar_width
plt.bar(index_lake, height=lake_num, width=bar_width, color='b', label='study_2020_lake')
plt.bar(index_TP, height=TP_lake_num, width=bar_width, color='g', label='TP_2020_lake')
plt.legend()
plt.xticks(index_lake + bar_width/2, area_class)
plt.ylabel('Number')
plt.xlabel('Area (km$^{2}$)')
plt.show()
df = pd.read_excel('path of file',sheet_name='Sheet1')
fig, ax = plt.subplots()
area_class = df['name']
lake_num = df['lake_number']
TP_lake_num = df['TP_2020_lake_number']
bar_width = 0.3
index_lake = np.arange(len(area_class))
index_TP = index_lake + bar_width
plt.bar(index_lake, height=lake_num, width=bar_width, color='b', label='study_lake')
for x, y in enumerate(df['lake_number'].values):
# plt.text(x, y+1,y,ha='center', va='bottom')
plt.text(x+0.1, y+1,y,ha='right',va='bottom')
plt.bar(index_TP, height=TP_lake_num, width=bar_width, color='g', label='TP_lake')
for a, b in enumerate(df['TP_2020_lake_number'].values):
plt.text(a+0.1, b+1,b,ha='left',va='bottom')
plt.legend()
plt.xticks(index_lake + bar_width/2, area_class)
plt.ylabel('Number')
plt.xlabel('Area (km$^{2}$)')
plt.show()
显示结果:
plt.text()函数参数说明:https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.text.html