python - 将颜色条与辅助 y 轴一起使用

标签 python matplotlib

我正在尝试向具有辅助 y 轴的图表添加颜色栏。下面给出了我的困难的一个最小的例子。问题是我无法将颜色条添加到 AxesSubplot 对象,并且直接将其添加为 plt.colorbar 将其放在我的图形顶部 - 查看它如何与最右边的 y 轴重叠。我怎样才能解决这个问题?干杯。

import matplotlib.pyplot as plt
import numpy as np
import scipy.interpolate

time=[]
temp=[]
temp_f=[]
height=[]
for ti in np.arange( 0, 10, 0.5 ):
    for te in np.arange( -12, 12, 0.5 ):
        height.append( np.sqrt(1+ti)/(1+te*te)+ti*te/12.5 )
        time.append(ti)
        temp.append(te)
        temp_f.append( 32+9.0*te/5)

time=np.array(time)
temp=np.array(temp)
temp_f=np.array(temp_f)
height=np.array(height)

xi, yi = np.linspace(time.min(), time.max(),25), np.linspace(temp.min(), temp.max(), 25)
xi, yi = np.meshgrid(xi, yi)

rbf = scipy.interpolate.Rbf(time, temp, height, function='linear')
zi = rbf(xi, yi)

fig = plt.figure()
ax1 = plt.gca()
ax1.set_xlabel( "Time (s)" )
ax1.set_ylabel( "Celsius" )

ax2 = ax1.twinx()
ax2.set_ylabel( "Fahrenheit" )
ax2.set_ylim( [temp_f.min(), temp_f.max()] )

img = ax1.imshow( zi, vmin=height.min(), vmax=height.max(), origin='lower', 
       extent=[time.min(), time.max(), temp.min(), temp.max()],
       aspect='auto', cmap='YlOrRd')

plt.colorbar(img, label=r"Height (cm)",format='%1.1f', ax=ax1)

plt.show()

最佳答案

参见 positioning the colorbar .

您可以通过以下方式手动指定颜色条的位置:

cbaxes = fig.add_axes([1, 0.15, 0.03, 0.7])
plt.colorbar(img, label=r"Height (cm)",format='%1.1f', ax=ax1, cax=cbaxes)

关于python - 将颜色条与辅助 y 轴一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31139108/

相关文章:

python - 减去 Pandas Dataframe 中的条目并存储在新列中

python - 完全相同的 python3 代码在 shell 中工作但不在脚本中工作?

python - 将不同的 seaborn 面网格组合成单个图

Python:我的带有五个进程的 python 程序使用了多少个内核?

python - matshow 的问题

python - 在 Python3 中使用 NetworkX 创建弯曲边缘

python - 将正态分布拟合到一维数据

python - 如何设置高水位线以阻止 pyzmq 中被淹没的收件人?

python - GeoPandas 绘图 - 有什么方法可以加快速度吗?

Python散点图根据值绘制不同的颜色