有没有办法绘制一条根据 Y 轴值改变颜色的线?就像Python中使用plt.plot的渐变线一样?

问题描述 投票:0回答:1

我有一个很大的数据集,其中包含几年来每天采集的温度。我想在图表上绘制温度。如何才能有一条连续线根据 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()

I am able to do it using the scatter function, but I want it to be a single continuous line.

Using a loop function just made it into loads of split lines which is not what I am trying to achieve

Tried creating two lines but then you have these awkward jumps and lines are not connected

尝试在 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

有人对我如何做到这一点有任何想法吗?

python matplotlib plot graph gradient
1个回答
0
投票

这是一个通过循环连续函数的片段来执行此操作的代码块。由于您有离散数据集,因此您必须对 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()

结果是:

© www.soinside.com 2019 - 2024. All rights reserved.