gpt4 book ai didi

python - matplotlib 图表背景取决于数据

转载 作者:行者123 更新时间:2023-12-01 09:30:16 24 4
gpt4 key购买 nike

我正在尝试绘制一些数据,并希望根据数据设置彩色背景。

在下面的示例中,我希望将 data1 和 data2 放在左侧 y 轴上,将 data3 放在右侧 y 轴上。这是有效的。但另外我尝试根据 data3 对背景进行着色。

我需要如何格式化数据才能使其正常工作?

import matplotlib.pyplot as plt
from datetime import datetime as dt
import matplotlib.dates as md

fig, ax1 = plt.subplots(constrained_layout=True)

data1 = [51.2, 51.2, 51.2, 50.7, 50.7, 50.5, 50.4, 50.7, 50.6]
data2 = [46.5, 46.1, 46.2, 46.3, 46.4, 46.3, 46.2, 46.1, 45.5]
data3 = [ 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0]

timestamps = [1524614516, 1524615134, 1524615587, 1524615910, 1524616235, 1524616559, 1524616866, 1524617189, 1524617511]
timestamps_ = [dt.utcfromtimestamp(x) for x in timestamps]

for data in (data1,data2):
ax1.plot(timestamps_, data, marker='.', linestyle='-')
ax1.set_ylabel("degC")

ax2 = ax1.twinx()
ax2.plot(timestamps_, data3, marker='x', linestyle='-')
ax2.pcolor(ax2.get_xlim(), ax2.get_ylim(), zip(timestamps_, data3), cmap='RdGn', alpha=0.3)
ax2.set_ylabel("ON OFF")

ax1.set_title("Mytitle")
for tick in ax1.xaxis.get_major_ticks():
tick.label1.set_horizontalalignment('right')
tick.label1.set_rotation(35)
xfmt = md.DateFormatter('%Y-%m-%d %H:%M:%S')
ax1.xaxis.set_major_formatter(xfmt)

plt.show()

错误消息:

Traceback (most recent call last):
File "/home/tobias/workspace/python_pyplot_test/main.py", line 25, in <module>
ax2.pcolor(ax2.get_xlim(), ax2.get_ylim(), zip(timestamps_, data3), cmap='RdGn', alpha=0.3)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/__init__.py", line 1855, in inner
return func(ax, *args, **kwargs)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_axes.py", line 5732, in pcolor
X, Y, C = self._pcolorargs('pcolor', *args, allmatch=False)
File "/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_axes.py", line 5576, in _pcolorargs
C.shape, Nx, Ny, funcname))
TypeError: Dimensions of C (9, 2) are incompatible with X (2) and/or Y (2); see help(pcolor)

最佳答案

这是您想要的最小解决方案:

import matplotlib.pyplot as plt
from datetime import datetime as dt
import matplotlib.dates as md
import numpy as np


data3 = np.array([ 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 0.0, 0.0])

x=np.arange(9)
xp,yp=np.meshgrid(x,data3)
xp=xp.astype(float)-0.5
bgcolor=np.ones(xp.shape)*data3[None,:]

plt.pcolor(xp,yp,bgcolor)
plt.plot(x, data3, marker='x', linestyle='-')

我取出了第二个轴和所有勾选的东西,因为它们与问题本身无关。

关于python - matplotlib 图表背景取决于数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50029418/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com