python-matplotlib画图相关

  1. 一张图中共用x轴,两个y轴,同时显示bar和line
import matplotlib.pyplot as plt
import pandas as pd

df = pd.read_csv("D:\data.csv")

# 同一张图中两个y轴,同时显示bar、line
for id in df["id"].unique():
    tmp = df[df["id"] == id]
    fig = plt.figure(figsize=(20, 8))
    ax = fig.add_subplot(111)
    ax.bar(tmp["d"], tmp["nums"], label="nums")

    ax2 = ax.twinx()
    ax2.plot(tmp["d"], tmp["ratio"], c="r", label="ratio")
    ax2.scatter(tmp["d"], tmp["ratio"], c="r")

    plt.gcf().autofmt_xdate()  # 自动调整日期
    plt.title(id)
    fig.legend(loc=1, bbox_to_anchor=(1, 1), bbox_transform=ax.transAxes)
    plt.savefig("D:\" + str(id) + ".png")
    plt.close(fig)

结果如下所示
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/yaogepila/article/details/127892704