I have a dataframe in which I have x and y values to be plotted using seaborn library. But the cache here is that I need to color the background with multiple colors based on the data points I already have. for example
# df - represents the dataframe in which the x and y data are present
split_points = [20,40,60,80,100] # The list of split point, the list can be bigger as well ( keeping it same with the example)
sns.scatterplot(...) # I need help with this to get the below specified graph
The snippet of code looks something like above. But I would typically like to get the split of all the points mentioned in the split_points list as different background colors. Hoping to find the method to do the same.
I intend to do something like this.
I have taken the image from this answer for better understanding.
You can use axvspan()
to add the background color for each region, along with alpha
to control the transparency and zorder
to move the colored rectangles to the back, so that the lines are on top. For the legend, you can use label
to provide the text in each case. Below is a working example. Hope this is what you are looking for...
df=np.random.uniform(low=-10, high=5, size=(100,)) ## data for the line
split_points = [20,40,60,80,100] # The list of split point, the list can be bigger as well ( keeping it same with the example)
split_colors = ['red', 'yellow', 'green', 'blue', 'pink'] ## Colors for each region
sns.lineplot(data=df, color='black', lw=0.75) ## Draw the line plot you want
labels=[*'abcde'] ## Define the labels for the legend
## For each entry, draw the rectangle along with the color, transparency, zorder and label for the legend
for i in range(len(split_points)):
plt.axvspan(split_points[i]-20, split_points[i], facecolor=split_colors[i], alpha=0.2, zorder=-10, label=labels[i])
plt.legend()
plt.show()