pyplot双y轴图
有时候在写文章比较effiency的时候会比较time和memory 这个时候可以用到双y轴。左边是time 右边是memory
# -*- coding:utf-8 -*-
from turtle import color
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import pyplot
from pydantic import ColorError
palette = pyplot.get_cmap('Set1')
font = {'family': 'serif',
'serif': 'Times New Roman',
'weight': 'normal',
'size': 15}
plt.rc('font', **font)
color = [
'#9bc4cb',
'#cfebdf',
'#e2fadb',
'#dbefbc',
'lightcoral',
#'coral',
#'darkorange',
#'gold',
'palegreen',
'paleturquoise',
'skyblue',
#'plum',
'hotpink',
'pink',
'Mistyrose']
# 创建数据
time = [1.45, 1.62 ,2.10, 1.67 ]
memory = [417.9, 421.3, 838.2, 835.9]
labels = ["Ours","FS_Stega", "SeSy", "Zou",]
plt.rcParams['axes.labelsize']=15
plt.rcParams['xtick.labelsize']=15
plt.rcParams['ytick.labelsize']=15
plt.rcParams['legend.fontsize']=12
width = 0.4
x1_list=[]
x2_list=[]#位置
for i in range(len(time)):
x1_list.append(width*i)
print(x1_list)
for i in range(len(time)):
x2_list.append(1.8+i*width)
print(x2_list)
t = np.arange(0.01, 10.0, 0.01)
fig,ax1 = plt.subplots()
ax1.set_ylabel('Time Cost (s)')
ax1.set_ylim([0,2.5])
ax1.set_xticks([])
ax1.bar(x1_list,time,width=width-0.1,color =color,align='edge')
#ax1.set_xticklabels(ax1.get_xticklabels())
for a,b in zip(x1_list,time): #柱子上的数字显示
plt.text(a+0.15,b,'%.2f'%b,ha='center',va='bottom',fontsize=12)
ax2 = ax1.twinx()
#ax2.set_ylabel("Y2",color='b')
ax2.set_ylabel('Memory Cost (MB)')
ax2.set_ylim([400,860]) #设置y轴范围
ax2.bar(x2_list[0],memory[0],width=width-0.1,color =color[0],align='edge',label =labels[0])
ax2.bar(x2_list[1],memory[1],width=width-0.1,color =color[1],align='edge',label =labels[1])
ax2.bar(x2_list[2],memory[2],width=width-0.1,color =color[2],align='edge',label =labels[2])
ax2.bar(x2_list[3],memory[3],width=width-0.1,color =color[3],align='edge',label =labels[3])
for a,b in zip(x2_list,memory): #柱子上的数字显示
plt.text(a+0.15,b,'%.1f'%b,ha='center',va='bottom',fontsize=12)
ax2.legend(ncol=2,loc ='lower left')
fig.tight_layout()
plt.show()
plt.savefig("timeandemory.pdf")