matplotlib-双柱状图(簇状柱形图)

某户全年每月的水电费统计如下。水费:20,25,37,38,38,48,50,55,53,38,25,28元,电费:220, 175, 198,187,190,260,350,320,330,230,290,330元。

请以月度为单位画出水费与电费的簇状柱形图。

 方法一

import matplotlib.pyplot as plt
plt.rcParams['font.family'] = 'kaiti' #解决中文乱码

month = [1,2,3,4,5,6,7,8,9,10,11,12]
month_fmt = ["{}月".format(i) for i in range(1,13)]

wt = [20,25,37,38,38,48,50,55,53,38,25,28] #水费
elt=[220, 175, 198, 187,190,260,350,320,330,230,290,330] #电费

#需要增加位移变量,不然会出现重叠现象
move = 0.4

# move=width 紧挨着
# move > width 有空隙
# move < width 重叠

#绘制水费柱状图
wt1=plt.bar(month,height = wt,width = 0.3,align = "center",color = "skyblue",label = "水费")

#绘制电费柱状图
elt2=plt.bar([i+move for i in month],height = elt,width = 0.3,align = "center",color =
"pink",label = "电费")

plt.bar_label(wt1, label_type='edge')
plt.bar_label(elt2, label_type='edge')
plt.xticks([i+move/2 for i in month],month_fmt)

plt.title('某户全年每月的水电费统计') # 标题
plt.xlabel('月份') # x轴标题
plt.ylabel('费用/元') # y轴标题
plt.legend()
plt.show()

 matplotlib-双柱状图(簇状柱形图)_第1张图片

方法二

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
plt.rcParams['font.family'] = 'kaiti'

month = ['1月','2月','3月','4月','5月','6月','7月','8月','9月','10月','11月','12月']
data = pd.DataFrame({'wt': [20,25,37,38,38,48,50,55,53,38,25,28],
'elt': [220, 175, 198, 187,190,260,350,320,330,230,290,330]
},index=month)

x = np.arange(len(month))
width = 0.3
fig, ax = plt.subplots(figsize=(6,4))

wt1 = ax.bar(x - width/2, data['wt'], width, label='水费')
elt2 = ax.bar(x + width/2, data['elt'], width, label='电费')

ax.bar_label(wt1, label_type='edge')
ax.bar_label(elt2, label_type='edge')

ax.set_ylabel('费用/元')
ax.set_title('某户全年每月的水电费统计')
ax.set_xticks(x)
ax.set(ylim=(0, 400))
ax.set_xticklabels(month)
ax.legend(loc = 2)
plt.show()

matplotlib-双柱状图(簇状柱形图)_第2张图片 

 

你可能感兴趣的:(matplotlib,python,开发语言)