今天遇上一个小的需求就是需要绘制双轴的图,这个之前使用excel的话是可以很快绘制出来的,但是基于代码实现的话好像还么怎么用过,所以这里研究了下,绘制好后,分享记录一下,首先看下数据:
主要是不同种类的编程开发相关的书籍的销售数据,首先加载数据:
# 数据加载
workbook = xlrd.open_workbook(data, encoding_override="utf-8")
table = workbook.sheets()[0]
row_num, col_num = table.nrows, table.ncols
data_list = []
for i in range(0, row_num):
one_list = []
for j in range(0, col_num):
try:
one_list.append(table.cell_value(i, j))
except Exception as e:
one_list.append(0)
data_list.append(one_list)
print("data_list_length: ", len(data_list))
之后对读取的数据进行解析处理:
# 数据计算
final2018 = 0
need_list = []
for one_list in data_list:
if one_list[0].strip() == book:
cell = one_list[-1]
try:
date = datetime.datetime(*xldate_as_tuple(cell, 0))
cell = date.strftime("%Y-%d-%m")
except Exception as e:
print("Exception: ", e)
print("cell: ", cell)
one_list[-1] = cell
if cell.startswith("2019"):
need_list.append(one_list)
if cell.startswith("2018-12"):
final2018 = sum([int(one) for one in one_list[3:10]])
else:
pass
print("need_list_length: ", len(need_list))
for one_list in need_list:
print(need_list)
print("final2018: ", final2018)
num_list = []
for one_list in need_list:
nums = [int(one) for one in one_list[3:10]]
num_list.append([one_list[-1], sum(nums)])
sorted_list = sorted(num_list, key=lambda e: e[0])
print(sorted_list)
x, y1, y2 = [], [], []
for i in range(len(sorted_list)):
x.append(i)
y1.append(sorted_list[i][1])
if i == 0:
try:
y2.append((sorted_list[i][1] - final2018) / final2018)
except:
y2.append(0)
else:
y2.append(
(sorted_list[i][1] - sorted_list[i - 1][1]) / sorted_list[i - 1][1]
)
最后是结果数据的可视化:
# 绘图
fig = plt.figure(figsize=(10, 8), facecolor="#00E5EE")
# 字体使用楷体
plt.rcParams["font.sans-serif"] = ["STKAITI"]
plt.rcParams["axes.unicode_minus"] = False
# 设置背景色
plt.rcParams["axes.facecolor"] = "#cc00ff"
ax1 = fig.add_subplot(111)
plt.title("《Python数据分析与应用》2019年环比增长情况", color="r", fontsize=25, y=1.04)
plt.xticks(
x,
["1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"],
color="b",
fontsize=20,
)
plt.xlabel("月份", color="b", fontsize=20)
plt.ylabel("全国销量(册)", color="b", fontsize=20)
ax1.bar(x, y1, color="#33ff66", label="left")
# 增加一条坐标轴
ax2 = ax1.twinx()
ax2.plot(x, y2, color="#3399ff", line, marker="o", linewidth=2)
ax2.set_ylabel("增长率", color="b", fontsize=20)
ax2.tick_params(axis="y", color="green", labelsize=20, labelcolor="#B22222")
for a, b in zip(x, y2):
plt.text(
a, b + 0.02, "%.2f" % b, ha="center", va="bottom", fontsize=20, color="red"
)
plt.show()
我们看下效果图:
看上去有点花里胡哨,当然了也可以去掉不需要的背景色:
这样看上去就好多了,可以看到:这里主要是做了一个简单的可视化,分析某种书籍的各个月份的销量情况,同时绘制了增长率的折线图,左轴和右轴的刻度也是不一样的。



