脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python实现双轴组合图表柱状图和折线图的具体流程

Python实现双轴组合图表柱状图和折线图的具体流程

2021-12-25 00:26bellin124 Python

这篇文章主要介绍了Python双轴组合图表柱状图+折线图,Python绘制双轴组合的关键在plt库的twinx()函数,具体实例代码跟随小编一起看看吧

python绘制双轴组合的关键在plt库的twinx()函数,具体流程:

1.先建立坐标系,然后绘制主坐标轴上的图表;

2.再调用plt.twinx()方法;

3.最后绘制次坐标轴图表。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
import cx_oracle
import xlrd
import xlwt
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import funcformatter
 
plt.rcparams['font.sans-serif']=['simhei']
plt.rcparams['axes.unicode_minus']=false
#设置坐标轴数值以百分比(%)显示函数
def to_percent(temp, position):
  return '%1.0f'%(1*temp) + '%'
#字体设置
font2 = {'family' : 'times new roman',
'weight' : 'normal',
'size'   : 25,
}
 
conn=cx_oracle.connect('用户名/密码@ip:端口/数据库')
c=conn.cursor()
#sql查询语句,多行用()括起来
sql_detail=("select substr(date1,6,10)date1,round(avg(r_qty))r_qty,round(avg(e_qty))e_qty,""round(avg(r_qty)/avg(e_qty),2)*100 userate,round(avg(uptime),2)*100 uptime from 表tp "
"tp where 条件  "
"group by date1 order by date1 "
                              
x=c.execute(sql_detail)
#获取sql查询数据                        
data=x.fetchall()
#print(data)
 
#新建excel保存数据
xl=xlwt.workbook()
ws=xl.add_sheet("robot 30 days move ")
#ws.write_merge(0,1,0,4,"robot_30_days_move")
for i,item in enumerate(data):
    for j,val in enumerate(item):
        ws.write(i,j,val)
xl.save("e:\\robot_30_days_move.xls")
 
#读取excel数据
data1 = xlrd.open_workbook( "e:\\robot_30_days_move.xls")
sheet1=data1.sheet_by_index(0)
 
date1=sheet1.col_values(0)
r_qty=sheet1.col_values(1)
e_qty=sheet1.col_values(2)
userate=sheet1.col_values(3)
uptime=sheet1.col_values(4)
 
#空值处理
for a in r_qty:
    if a=='':
        a=0
for a in e_qty:
    if a=='':
        a=0
for a in userate:
    if a=='':
        a=0
for a in uptime:
    if a=='':
        a=0
#将list元素str转int类型
r_qty = list(map(int, r_qty))
e_qty = list(map(int, e_qty))
userate = list(map(int, userate))
uptime = list(map(int, uptime))
#添加平均值mean求平均
r_qty.append(int(np.mean(r_qty)))
e_qty.append(int(np.mean(e_qty)))
userate.append(int(np.mean(userate)))
uptime.append(int(np.mean(uptime)))
date1.append('avg')
 
#x轴坐标
x=np.arange(len(date1))
bar_width=0.35
 
plt.figure(1,figsize=(19,10))
#绘制主坐标轴-柱状图
plt.bar(np.arange(len(date1)),r_qty,label='rbt_move',align='center',alpha=0.8,color='blue',width=bar_width)
plt.bar(np.arange(len(date1))+bar_width,e_qty,label='eqp_move',align='center',alpha=0.8,color='orange',width=bar_width)
 
#设置主坐标轴参数
plt.xlabel('')
plt.ylabel('move',fontsize=18)
plt.legend(loc=1, bbox_to_anchor=(0,0.97),borderaxespad = 0.)
#plt.legend(loc='upper left')
for x,y in enumerate(r_qty):
    plt.text(x,y+100,'%s' % y,ha='center',va='bottom')
for x,y in enumerate(e_qty):
    plt.text(x+bar_width,y+100,'%s' % y,ha='left',va='top')
plt.ylim([0,8000])
 
#调用plt.twinx()后可绘制次坐标轴
plt.twinx()
 
#次坐标轴参考线
target1=[90]*len(date1)
target2=[80]*len(date1)
 
x=list(range(len(date1)))
plt.xticks(x,date1,rotation=45)
 
#绘制次坐标轴-折线图
plt.plot(np.arange(len(date1)),userate,label='use_rate',color='green',linewidth=1,linestyle='solid',marker='o',markersize=3)
plt.plot(np.arange(len(date1)),uptime,label='uptime',color='red',linewidth=1,linestyle='--',marker='o',markersize=3)
 
plt.plot(np.arange(len(date1)),target1,label='90%target',color='black',linewidth=1,linestyle='dashdot')
plt.plot(np.arange(len(date1)),target2,label='80%target',color='black',linewidth=1,linestyle='dashdot')
 
#次坐标轴刻度百分比显示
plt.gca().yaxis.set_major_formatter(funcformatter(to_percent))
 
plt.xlabel('')
plt.ylabel('rate',fontsize=18)
#图列
plt.legend(loc=2, bbox_to_anchor=(1.01,0.97),borderaxespad = 0.)
plt.ylim([0,100])
for x,y in enumerate(userate):
    plt.text(x,y-1,'%s' % y,ha='right',va='bottom',fontsize=14)
for x,y in enumerate(uptime):
    plt.text(x,y+1,'%s' % y,ha='left',va='top',fontsize=14)
 
plt.title("robot 30 days move")
 
#图表table显示plt.table()
listdata=[r_qty]+[e_qty]+[userate]+[uptime]#数据
table_row=['rbt_move','eqp_move','use_rate(%)','uptime(%)']#行标签
table_col=date1#列标签
print(listdata)
print(table_row)
print(table_col)
 
the_table=plt.table(celltext=listdata,cellloc='center',rowlabels=table_row,collabels=table_col,rowloc='center',colloc='center')
#table参数设置-字体大小太小,自己设置
the_table.auto_set_font_size(false)
the_table.set_fontsize(12)
#table参数设置-改变表内字体显示比例,没有会溢出到表格线外面
the_table.scale(1,3)
#plt.show()
 
plt.savefig(r"e:\\robot_30_days_move.png",bbox_inches='tight')
#关闭sql连接
c.close()                                                     
conn.close()

结果显示:

Python实现双轴组合图表柱状图和折线图的具体流程

到此这篇关于python实现双轴组合图表柱状图和折线图的具体流程的文章就介绍到这了,更多相关python柱状图和折线图内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://www.cnblogs.com/bellin124/p/14610744.html

延伸 · 阅读

精彩推荐