(4-1-2)绘制柱状图:绘制基本的柱状图(2)

4.1.5  绘制堆叠柱状图

请看下面的实例文件bar06-3.py,功能是使用库matplotlib绘制堆叠柱状图。

源码路径:codes\4\4-1\bar06-3.py

import numpy as np
import matplotlib.pyplot as plt

size = 5
x = np.arange(size)
a = np.random.random(size)
b = np.random.random(size)
plt.bar(x, a, label='a')
plt.bar(x, b, bottom=a, label='b')
plt.legend()
plt.show()

执行效果如图4-10所示。

图4-10  执行效果

4.1.6  绘制并列柱状图

请看下面的实例文件bar06-4.py,功能是使用库matplotlib绘制并列柱状图。

源码路径:codes\4\4-1\bar06-4.py

import numpy as np
import matplotlib.pyplot as plt

size = 5
x = np.arange(size)
a = np.random.random(size)
b = np.random.random(size)
c = np.random.random(size)

total_width, n = 0.8, 3
width = total_width / n
x = x - (total_width - width) / 2

plt.bar(x, a, width=width, label='a')
plt.bar(x + width, b, width=width, label='b')
plt.bar(x + 2 * width, c, width=width, label='c')
plt.legend()
plt.show()

执行效果如图4-11所示。

图4-11  执行效果

4.1.7  绘制2002~2013年网页浏览器使用变化柱状图

使用库pygal绘制柱状图的方法十分简单,只需调用库pygal中的Bar()方法即可。例如在下面的实例文件bar07.py中,绘制了2002~2013年网页浏览器的使用变化数据的柱状图。

源码路径:codes\4\4-1\bar07.py

import pygal

line_chart = pygal.Bar()
line_chart.title = '网页浏览器的使用变化(in %)'
line_chart.x_labels = map(str, range(2002, 2013))
line_chart.add('Firefox', [None, None, 0, 16.6,   25,   31, 36.4, 45.5, 46.3, 42.8, 37.1])
line_chart.add('Chrome',  [None, None, None, None, None, None,    0,  3.9, 10.8, 23.8, 35.3])
line_chart.add('IE',      [85.8, 84.6, 84.7, 74.5,   66, 58.6, 54.7, 44.8, 36.2, 26.6, 20.1])
line_chart.add('Others',  [14.2, 15.4, 15.3,  8.9,    9, 10.4,  8.9,  5.8,  6.7,  6.8,  7.5])
line_chart.render_to_file('bar_chart.svg')

执行后会创建生成条形图文件bar_chart.svg,打开后的效果如图4-12所示。

图4-12  生成的条形图文件bar_chart.svg

4.1.8  绘制直方图

使用库pygal绘制直方图的方法十分简单,只需调用库pygal中的Histogram()方法即可。例如在下面的实例文件bar08.py中,使用Histogram()方法分别绘制了宽直方图和窄直方图。

源码路径:codes\4\4-1\bar08.py

import pygal
hist = pygal.Histogram()
hist.add('Wide bars', [(5, 0, 10), (4, 5, 13), (2, 0, 15)])
hist.add('Narrow bars',  [(10, 1, 2), (12, 4, 4.5), (8, 11, 13)])
hist.render_to_file('bar_chart.svg')

执行后会创建生成直方图文件bar_chart.svg,打开后的效果如图4-13所示。

图4-13  生成的直方图文件bar_chart.svg

  • 8
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

码农三叔

感谢鼓励

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值