我有一个很大的数据集,其中包含几年来每天采集的温度。我想在图表上绘制温度。如何才能有一条连续线根据 Y 值是否高于或低于 0 度来改变两种颜色?
这是我能达到的最接近我想要的最终外观的效果。然而,这是一个散点图而不是一条线......
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
#'Date' is the combined datetime column, and 'T' is the temperature column
plt.plot(df['Date'], df['T'], c=df['T'] < 0, cmap='bwr', marker='.')
plt.xlabel('Year')
plt.ylabel('Temperature')
plt.title('Temperature Over Time')
# Formatted x-axis labels to display only years
plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y'))
plt.gca().xaxis.set_major_locator(mdates.YearLocator())
plt.colorbar(label='Temperature (°C)')
plt.show()
尝试在 plt.plot 中执行“if”“else”,但这也不起作用,当我删除标记='.'时我的 plt.plot 只是出现值错误
raise ValueError(f"{v!r} is not a valid value for {k}")
这么说Name: T, Length: 5848, dtype: bool is not a valid value for color
有人对我如何做到这一点有任何想法吗?
这是一个通过循环连续函数的片段来执行此操作的代码块。由于您有离散数据集,因此您必须对 y 轴值进行插值才能找到分配的颜色。
scipy.interpolate
库可能会对此有所帮助。
import numpy as np
import matplotlib.pyplot as plt
# Create a sample continuous curve
x = np.linspace(0, 10, 50)
y = np.sin(x)
# Define colors based on y-values
colors = plt.cm.viridis(y / max(y))
# Plot the graph segment by segment; each segment corresponds to a different color
for i in range(len(x) - 1):
plt.plot(x[i:i+2], y[i:i+2], color=colors[i])
plt.xlabel('X')
plt.ylabel('Y')
plt.title('Gradient Line Plot')
plt.show()
结果是: