matplotlib:次坐标轴ax2=ax1.twinx()

本文展示了一个使用Python的matplotlib库进行双轴绘图的例子。通过创建两个共享相同x轴但有独立y轴的数据集,文章详细介绍了如何在一个图表中同时绘制两个不同尺度的数据系列,并设置了不同的颜色和标签以区分每个y轴。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

import numpy as np
import matplotlib
matplotlib.use(“TkAgg”)
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.gridspec as gridspec

x=np.arange(0,10,0.1)
y1=0.05x**2
y2=-1
y1

fig,ax1=plt.subplots()
ax2=ax1.twinx()#产生一个ax1的镜面坐标
ax1.plot(x,y1,“g-”)
ax2.plot(x,y2,“b–”)

ax1.set_xlabel(“X data”)
ax1.set_ylabel(“Y1”,color=“g”)
ax2.set_ylabel(“Y2”,color=“b”)

plt.show()
在这里插入图片描述

更改以下代码使得图例Tem图例Pre的左边:import numpy as np import pandas as pd import matplotlib.pyplot as plt #from matplotlib.font_manager import FontProperties plt.rcParams['font.sans-serif'] = ['SimSun'] plt.rcParams['axes.unicode_minus'] = False #读取数据 data = pd.read_csv(r"D:\Python\T&P.csv") year = data['year'].values temp = data['temp'].values prec = data['prec'].values #设置画布和轴 fig = plt.figure(figsize = (7,4)) ax1 = fig.subplots() ax2 = ax1.twinx() #折线图设置 ax1.plot(year, temp) ax1.plot(year, temp, color = 'red', linestyle = '-', linewidth = 2, marker = 'o', markersize = 5, markerfacecolor = 'white') #坐标轴设置 ax1.set(xlim = (1980,2021), ylim = (25,40), xticks = np.arange(1980,2021,10), yticks = np.arange(25,40,5)) ax1.tick_params(labelsize = 10, pad = 5, length = 4) ax2.set(xlim = (1980,2021), ylim = (0,400), xticks = np.arange(1980,2021,10), yticks = np.arange(0,410,100)) ax2.spines['left'].set_color('red') ax2.spines['right'].set_color('tab:blue') ax2.tick_params(axis = 'y', color = 'tab:blue') ax1.tick_params(axis = 'y', labelcolor = 'red') #坐标标题 ax1.set_xlabel('年(公元)') ax1.set_ylabel('Temperature(℃)', color = 'red') ax2.set_ylabel('Precipitation(mm)', color = 'tab:blue') #图例设置 ax1.legend(['Pre', 'Tem'], ncol = 2, markerscale = 1, frameon= False) #柱状图设置 ax2.bar(year, prec, width = 0.3, color = 'tab:blue', edgecolor = 'tab:blue', linewidth = 1, align='center') ax1.set(xlim = (1980,2021), ylim = (10,40), xticks = [1981, 1990, 2000, 2010, 2020], yticks = np.arange(10, 45, 5)) plt.show()
04-03
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值