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

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

年份2007200820092010201120122013201420152016
手机网民规模5040117602334430274355584199750006556786200069500
手机网民占比0.240.3950.6080.6620.6930.7450.8100.8580.9010.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()
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值