Skip to main content
 首页 » 编程设计

python之线条颜色取决于趋势

2025年01月19日10虾米哥

我正在尝试绘制一条线,该线应该以代表图表趋势的方式着色。例如,如果它正在增加,它应该是绿色的,而如果它正在减少,它应该是红色的。

我可以简单地使用移动的数据框来表示这种趋势绘图点:

dates = ['2018-01-{}'.format(d) for d in range(1, 32)] 
vals = [1, 2, 3, 4, 6, 9, 12, 11, 10, 8, 4, 10, 15, 17, 17, 18, 18, 17, 16, 19, 22, 23, 23, 25, 28, 33, 30, 25, 24, 
        20, 18] 
 
df = pd.DataFrame(data=vals, columns=['Value']) 
df.set_index(pd.to_datetime(dates), inplace=True) 
 
df_shifted = df.shift() 
df_shifted.iloc[0] = df_shifted.iloc[1] 
mask_inc = df >= df_shifted 
df['Increase'] = mask_inc['Value'] 
 
fig, ax = plt.subplots() 
ax.plot(df['Value'], color='#ededed') 
 
color = {True: 'green', False: 'red'} 
for index, row in df.iterrows(): 
    ax.plot(index, row['Value'], 'o', color=color[row['Increase']]) 

我知道 matplotlib 不允许在同一条线图中使用不同的颜色,但是否有任何解决方法而不会使它变得非常复杂?

我考虑过使用 Increase mask 绘制两个不同的数据帧,但问题是该线会被连续绘制,因此所有点都会连接起来,而我需要将它分成由线段组成的不同部分。

请您参考如下方法:

可以关注this tutorial实现你想要的。

然后您可以使用以下代码:

import numpy as np 
import matplotlib.pyplot as plt 
from matplotlib.collections import LineCollection 
from matplotlib.colors import ListedColormap, BoundaryNorm 
import datetime 
 
max_range = 32 
dates = ['2018-01-{}'.format(d) for d in range(1, max_range)] 
x = np.asarray(range(1,max_range)) 
y = [1, 2, 3, 4, 6, 9, 12, 11, 10, 8, 4, 10, 15, 17, 17, 18, 18, 17, 16, 19, 22, 23, 23, 25, 28, 33, 30, 25, 24, 
        20, 18] 
y = np.asarray(y) 
z = [i - j for i, j in zip(y[:-1], y[1:])] 
z = np.asarray(z) 
 
# Create a colormap for red, green and blue and a norm to color 
# f' < -0.5 red, f' > 0.5 blue, and the rest green 
cmap = ListedColormap(['g', 'b', 'r']) 
norm = BoundaryNorm([-100, -0.5, 0.5, 100], cmap.N) 
 
# Create a set of line segments so that we can color them individually 
# This creates the points as a N x 1 x 2 array so that we can stack points 
# together easily to get the segments. The segments array for line collection 
# needs to be numlines x points per line x 2 (x and y) 
points = np.array([x, y]).T.reshape(-1, 1, 2) 
segments = np.concatenate([points[:-1], points[1:]], axis=1) 
 
# Create the line collection object, setting the colormapping parameters. 
# Have to set the actual values used for colormapping separately. 
lc = LineCollection(segments, cmap=cmap, norm=norm) 
lc.set_array(z) 
lc.set_linewidth(3) 
 
fig1 = plt.figure() 
plt.gca().add_collection(lc) 
plt.xlim(0,max_range-1) 
plt.ylim(min(y), max(y)) 
plt.xticks(x,dates, rotation='vertical') 
plt.tight_layout() 
plt.show() 

生成以下绘图: