python plt 一张图两个y轴,图例legend合并

参考:

【Python】matplotlib 双y轴绘制及合并图例 - Vincent丶丶 - 博客园

代码示例:

from tkinter import font
from matplotlib.font_manager import FontProperties
import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt
import matplotlib
matplotlib.rcParams['font.sans-serif'] = ['KaiTi'] #或者把"SimHei"换为"KaiTi"
matplotlib.rcParams['axes.unicode_minus'] = False  # 解决保存图像是负号'-'显示为方块的问题
plt.style.use('/home/wzg/data1/LSTM-temporal-smooth-new2/plt_file/thu_figure.mplstyle')

data = pd.read_csv("/home/wzg/data1/LSTM-temporal-smooth-new2/"+\
    "work0_review/surveillance video anomaly detection.csv")

year = data["year"].values[:-1]
publication =  data["publication"].values[:-1]
index =  data["index"].values[:-1]

# color = 'blue'
fig = plt.figure(figsize=(15,6))
color=(188/255,155/255,254/255)

ax1 = fig.add_subplot(111)#lt.subplots(figsize=(10,6))
_bars_ = ax1.bar(year,publication,color=color,label="出版物")
ax1.set_xlabel("时间")
ax1.set_ylabel("出版物",color=color)
ax1.tick_params(axis='y',labelcolor=color)
# ax1.legend()

color=(61/255,15/255,201/255)
ax2 = ax1.twinx()
_lines_, = ax2.plot(year,index,color=color,label="被引频次")
ax2.set_ylabel("被引频次",color=color)
ax2.tick_params(axis='y',labelcolor=color)
# ax2.legend()

lns = [_bars_,_lines_]
labels = [l.get_label() for l in lns]
plt.legend(lns,labels)

plt.tight_layout()
plt.savefig("/home/wzg/data1/LSTM-temporal-smooth-new2/work0_review"+\
    "/ano_paper_trend.pdf",dpi=300)


plt.show()


注意事项:"_lines_"后面要有个逗号,否则 “_lines_.get_label()”会报错。

_lines_, = ax2.plot(year,index,color=color,label="被引频次")

你可能感兴趣的:(plt)