Python绘制柱状图
1.1Python绘制柱状图对应代码如下所示
import matplotlib.pyplot as plt import numpy as np from pylab import mpl mpl.rcParams['font.sans-serif'] = ['STZhongsong'] # 指定默认字体:解决plot不能显示中文问题 mpl.rcParams['axes.unicode_minus'] = False x=["孙悟空","唐僧","猪八戒","沙悟净"] y=[4,1,3,2] plt.bar(x,y,width=0.5,align="center",label="战力值",color="red") plt.title("师徒战力排行榜",loc="center") for a,b in zip(x,y): plt.text(a,b,b,ha='center',va="bottom",fontsize=12) plt.xlabel('姓名') plt.ylabel('战力值') plt.legend() plt.show()
1.2、最终结果如下图所示
1.3Python绘制横向柱状图
import matplotlib.pyplot as plt import numpy as np from pylab import mpl mpl.rcParams['font.sans-serif'] = ['STZhongsong'] # 指定默认字体:解决plot不能显示中文问题 mpl.rcParams['axes.unicode_minus'] = False x=["孙悟空","唐僧","猪八戒","沙悟净","牛魔王","哪吒","二郎神"] y=[10,1,6,5,7,8,9] plt.barh(x,width=y,height=0.6,align="center",label="战力值",color="green",edgecolor="rgb") ''' width 表示柱子的宽度,每根柱子的宽度可以都一样,也可以各不相同 align center:表示柱子位于x值的中心位置,edge:表示柱子位于x值的右边 color 柱子的颜色 edgecolor 柱子边缘的颜色 ''' plt.title("战力排行榜",loc="center") for a,b in zip(x,y): plt.text(b,a,b,ha='center',va="bottom",fontsize=12) plt.xlabel('姓名') plt.ylabel('战力值') plt.legend() plt.show()
1.4最终结果如下图所示
1.5Python绘制堆叠柱状图
import matplotlib.pyplot as plt import numpy as np from pylab import mpl mpl.rcParams['font.sans-serif'] = ['STZhongsong'] # 指定默认字体:解决plot不能显示中文问题 mpl.rcParams['axes.unicode_minus'] = False x=["唐僧","孙悟空","猪八戒","沙悟净"] y1=[10,6,3,7] y2=[3,10,7,6] list3=[] for i in range(len(y1)): new_value=y1[i]+y2[i] list3.append(new_value) plt.bar(x,y1,width=0.3,label="魅力值",color="orange") plt.bar(x,y2,width=0.3,label="武力值",color="red",bottom=y1) plt.title("师徒战力排行榜") for a,b in zip(x,y1): plt.text(a,b,b,ha='center',va="top",fontsize=12) for a,b,c in zip(x,list3,y2): plt.text(a,b,c,ha='center',va="bottom",fontsize=12) plt.xlabel('姓名') plt.ylabel('魅力值') plt.legend(loc="best") plt.show()
1.6最终结果如下图所示
1.7Python绘制并列柱状图
import matplotlib.pyplot as plt import numpy as np from pylab import mpl mpl.rcParams['font.sans-serif'] = ['STZhongsong'] # 指定默认字体:解决plot不能显示中文问题 mpl.rcParams['axes.unicode_minus'] = False plt.subplot(1,1,1) x=np.array([1,2,3,4]) y1=[10,6,3,7] y2=[3,10,7,6] plt.bar(x,y1,width=0.3,align="center",label="魅力值") plt.bar(x+0.3,y2,width=0.3,align="center",label="武力值") plt.title("师徒战力排行榜") for a,b in zip(x,y1): plt.text(a,b,b,ha='center',va="bottom",fontsize=12) for a,b in zip(x+0.3,y2): plt.text(a,b,b,ha='center',va="bottom",fontsize=12) plt.xlabel('姓名') plt.ylabel('魅力值') plt.xticks(x+0.15,["唐僧","孙悟空","猪八戒","沙悟净"]) plt.legend() plt.show()
1.8最终结果如下所示