如何在折线图中的线条之间绘制阴影?

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

我想根据线条显示的值之间的差异是负数还是正数来绘制两种不同颜色的阴影,我该怎么做?

这是我的意思的一个例子:

如有其他建议,我们将不胜感激。

这是我的代码:

#chart
plt.figure(figsize= (15, 4))
sns.lineplot(data=new_base, x='NumSettimana', y='Search2023', color ='#66875C', linewidth= 2)
sns.lineplot(data=new_base, x='NumSettimana', y='Search2022', color= 'blue', alpha=0.3, linestyle= 'dotted')
plt.grid(True, alpha=.3)

plt.fill_between(wallap['NumSettimana'], wallap['Search2022'], wallap['Search2023'], color='#66875C', alpha=0.15)

#labels
plt.xlabel('Week')
plt.ylabel('Google Trends')
plt.title('Change in GoogleTrends over a year', pad=15)
python pandas plotly seaborn
1个回答
0
投票

要根据线条显示的值之间的差异是负数还是正数来绘制两种不同颜色的阴影,可以使用 matplotlib 中的

fill_between
函数和条件着色。您可以通过以下方式修改代码来实现此目的:

import matplotlib.pyplot as plt
import seaborn as sns

# Assuming you have two dataframes 'new_base' and 'wallap' with columns 'NumSettimana', 'Search2022', and 'Search2023'

# Calculate the difference between Search2022 and Search2023
difference = wallap['Search2023'] - wallap['Search2022']

# Create a figure
plt.figure(figsize=(15, 4))

# Plot the line for Search2023
sns.lineplot(data=new_base, x='NumSettimana', y='Search2023', color='#66875C', linewidth=2)

# Plot the line for Search2022 with a dotted linestyle and lower alpha
sns.lineplot(data=new_base, x='NumSettimana', y='Search2022', color='blue', alpha=0.3, linestyle='dotted')

# Create a conditional fill_between to color the shadow based on the sign of 'difference'
plt.fill_between(wallap['NumSettimana'], wallap['Search2022'], wallap['Search2023'], 
                 where=(difference >= 0), color='green', alpha=0.15)  # Positive difference, green shadow

plt.fill_between(wallap['NumSettimana'], wallap['Search2022'], wallap['Search2023'], 
                 where=(difference < 0), color='red', alpha=0.15)    # Negative difference, red shadow

# Labels and title
plt.xlabel('Week')
plt.ylabel('Google Trends')
plt.title('Change in Google Trends over a year', pad=15)

# Show the grid
plt.grid(True, alpha=0.3)

# Show the plot
plt.show()

在此代码中,我们计算

Search2023
Search2022
之间的差异,然后使用两个
fill_between
调用根据差异的符号创建具有不同颜色的阴影(绿色表示正差异,红色表示负差异) 。这样,您就可以用两种不同的颜色获得所需的阴影效果。

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