干货|使用Python制作柱状图!

本文目标在于利用 Python快速画出符合自己要求的柱状图。

加载库

import matplotlib.pyplot as plt
import matplotlib.font_manager as mfm
from matplotlib import style
style.use('ggplot')  # 加载'ggplot'风格
# 加载中文字体
font_path = "/System/Library/Fonts/STHeiti Light.ttc" # 本地字体链接
prop = mfm.FontProperties(fname=font_path)

单一柱图

其中 t o t a l [ i ] total[i]total[i] 表示分数在 [ i ∗ 10 , ( i + 1 ) ∗ 10 ] [i*10,(i+1)*10][i∗10,(i+1)∗10] 区间内的人数。

total = [3, 5, 6, 7, 8, 6, 4, 3, 3, 22, 4, 8, 7, 13, 7, 7, 15, 10, 6, 52, 8, 2, 3, 26, 1, 1, 0, 2, 0, 3

如果直接对于上述数据执行下述代码,将得到如下结果。

plt.bar(range(len(total)), total)
plt.title('单一柱图', fontproperties=prop)
plt.savefig("单一柱图.png", dpi=700, fontproperties=prop)
plt.show()

在这里插入图片描述

不难发现,上述结果的效果不好。

首先第一点,分数段是 [ 0 , 300 ] [0,300][0,300],而此处显示的是 / 10 /10/10 后的数值。

其次,最后一根柱子没有数据显示,但其实应该显示 [ 290 , 300 ] [290,300][290,300] 的数据,因此我们需要对此进行改进。

自定义横坐标

因此我们选择自定义横坐标的方式来进行效果改进,具体代码如下。

x_labels = []
for item in range(0, 300, 10):
x = item + 10
if x == 10:
x_labels.append("{}~{}".format(0, 10))
elif x % 50 == 0:
x_labels.append("{}".format(x))
else:
x_labels.append(None)
x = range(len(total))
plt.bar(x, total)
plt.title('单一柱图', fontproperties=prop)
plt.xticks(x, x_labels)
plt.savefig("单一柱图.png", dpi=700, fontproperties=prop)
plt.show()

横坐标还可以调整字体大小以及旋转角度:

plt.xticks(x, x_labels, rotation=30, fontsize=5)

我们在 30 3030 个区间中仅选取了一部分进行标注,以及令第一个区间以 0 ~ 10 0~100~10 的方式进行显示。

在这里插入图片描述

多柱图

在展示完单一柱图之后,我们进入多柱同时显示的代码内容。首先是数据内容的展示,A [ i ] [ j ] A[i][j]A[i][j] 表示第 i ii 题得分在 [ j ∗ 10 , ( j + 1 ) ∗ 10 ] [j*10,(j+1)*10][j∗10,(j+1)∗10] 范围内的人数。

A = [[28, 3, 5, 6, 3, 7, 2, 4, 9, 95],
[58, 6, 13, 13, 5, 12, 17, 11, 10, 102],
[60, 22, 21, 41, 11, 5, 1, 2, 3, 4]]

然后我们执行下述代码即可得到下述多柱图。

# 生成横坐标
x_labels = []
for item in range(0, 100, 10):
x = item + 10
if x == 10:
x_labels.append("{}~{}".format(0, 10))
else:
x_labels.append("{}".format(x))
# 生成横坐标范围
x = np.arange(10)
# 生成多柱图
plt.bar(x + 0.00, A[0], color='orange', width=0.3, label="A")
plt.bar(x + 0.30, A[1], color='royalblue', width=0.3, label="B")
plt.bar(x + 0.60, A[2], color='brown', width=0.3, label="C")
# 图片名称
plt.title('多柱图', fontproperties=prop)
# 横坐标绑定
plt.xticks(x + 0.30, x_labels)
# 生成图片
plt.legend(loc="best")
plt.savefig("多柱图.png", dpi=700, fontproperties=prop)
plt.show()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值