使用matplotlib绘制中国手机网民占比图,将折线图和柱状图整合在一个图中等

本博客主要用来记录之前绘制一个复杂图表的过程。已有数据:2007-2016年10年间每年手机网民规模和手机网民占整体网民比例数据。

年份 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016
手机网民规模 5040 11760 23344 30274 35558 41997 50006 55678 62000 69500
手机网民占比 0.24 0.395 0.608 0.662 0.693 0.745 0.810 0.858 0.901 0.951

需求:将手机网民规模用柱状图进行显示,手机网民占比用折线图进行展示。
首先展示下结果图:

这里写图片描述

绘图代码如下:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

zhfont_kai = matplotlib.font_manager.FontProperties(fname='C:\Windows\Fonts\simkai.ttf')
zhfont_hei = matplotlib.font_manager.FontProperties(fname='C:\Windows\Fonts\simhei.ttf')

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x()-rect.get_width()/4, 1.02*height, "%s" % int(height))

width=1.5
index = np.arange(0, 30, 3)
print(index)
y = [5040, 11760, 23344, 30274, 35558, 41997, 50006, 55678, 62000, 69500]
y1 = np.array(y)
x1 = index + 1
fig = plt.figure()
ax1 = fig.add_subplot(111)
rect = ax1.bar(x1, y1, width, facecolor='#9999ff', edgecolor='white', label=u"手机网民规模")
ax1.set_ylabel("网民规模(万人)", fontproperties=zhfont_kai)
x = ['2007', '2008', '2009', '2010', '2011', '2012', '2013', '2014', '2015', '2016']
plt.xticks(index+1+width/2, x)
plt.ylim(0, 80000)
autolabel(rect)

ax2 = ax1.twinx()
x2 = index + 1.5
y2 = [0.24, 0.395, 0.608, 0.662, 0.693, 0.745, 0.810, 0.858, 0.901, 0.951]
rect2 = ax2.plot(x2, y2, 'r', marker="x", label=u"手机网民占整体网民比例")
#ax2.set_ylabel("占比", fontproperties=zhfont_kai)
ax2.set_ylim(0, 1)
y = ['0%', '20%', '40%', '60%', '80%', '100%']
plt.yticks(np.arange(0, 1.1, 0.2), y)
str_y = ['24%', '39.5%', '60.8%', '66.2%', '69.3%', '74.5%', '81.0%', '85.8%', '90.1%', '95.1%']
count = 0
for xy in zip(x2,y2):
    plt.annotate(str_y[count], xy=xy, xytext=(-10,10), textcoords='offset points')
    count = count + 1
plt.xlim(-0.5,30.5)

ax1.spines['top'].set_color('none')
plt.title("中国手机网民规模及其占网民比例", fontproperties=zhfont_hei)

ax2.spines['top'].set_color('None')
ax1.xaxis.set_ticks_position('bottom')
ax2.xaxis.set_ticks_position('bottom')

#l1 = plt.legend(loc='upper left', prop=zhfont_kai)
l1 = ax1.legend(loc=(.02,.92), fontsize=16, prop=zhfont_kai)
l2 = ax2.legend(loc=(.02,.83), fontsize=16, prop=zhfont_kai)

plt.savefig('网民.png')
plt.savefig('网民.jpg')
plt.show()

猜你喜欢

转载自blog.csdn.net/hohaizx/article/details/80992440
今日推荐