2

I have a dataframe (x, y, color), I am trying to change the background color whenever "color" changes value.

My result so far has the background color offset:

Results so far

I want the image the colors to align with the change in color value.

Here is the datafrane and the code I ran:

           y     x  color
0   0.691409  1.0   0    
1   0.724816  2.0   0    
2   0.732036  3.0   0    
3   0.732959  4.0   0    
4   0.734869  5.0   1    
5   0.737061  6.0   2    
6   0.717381  7.0   2    
7   0.704016  8.0   2    
8   0.693450  9.0   2    
9   0.684942  10.0  2    
10  0.674619  11.0  3    
11  0.677481  12.0  3    
12  0.680656  13.0  3    
13  0.682392  14.0  3    
14  0.682875  15.0  3    
15  0.685440  16.0  4    
16  0.678730  17.0  4    
17  0.666658  18.0  4    
18  0.659457  19.0  4    
19  0.652272  20.0  4    
20  0.647092  21.0  4    
21  0.645269  22.0  5    
22  0.649014  23.0  5    
23  0.652543  24.0  5    
24  0.653829  25.0  5    
25  0.655604  26.0  5    
26  0.656557  27.0  6    
27  0.647886  28.0  6    
28  0.642036  29.0  6  

The plot :


fix, ax= plt.subplots()
ax.plot(df['x'], df['y'])
ax.pcolorfast(ax.get_xlim(), ax.get_ylim(),
              df['color'].values[np.newaxis],
              cmap='Set3', alpha=0.3), 
plt.xticks(df['x'][::2])
#DRAWING EXPECTED LINES 

ax.axvline(x=6)
ax.axvline(x=11)
ax.axvline(x=16)
ax.axvline(x=22)
ax.axvline(x=27)
plt.show()

1 Answer 1

6

Not ideal, but this works.

from matplotlib.patches import Patch

fix, ax= plt.subplots()
ax.plot(df['x'], df['y'])

cmap = matplotlib.cm.get_cmap('Set3')
for c in df['color'].unique():
    bounds = df[['x', 'color']].groupby('color').agg(['min', 'max']).loc[c]
    ax.axvspan(bounds.min(), bounds.max()+1, alpha=0.3, color=cmap.colors[c])

legend = [Patch(facecolor=cmap.colors[c], label=c) for c in df['color'].unique()]
ax.legend(handles=legend)             
plt.xticks(df['x'][::2])
plt.xlim([df['x'].min(), df['x'].max()])
#DRAWING EXPECTED LINES 

ax.axvline(x=6)
ax.axvline(x=11)
ax.axvline(x=16)
ax.axvline(x=22)
ax.axvline(x=27)
plt.show()

With legend

Sign up to request clarification or add additional context in comments.

2 Comments

it works, but is leaving a lot of white space around the edge. Can a legend with the colors be added ?
Where do you mean white space? 1> or >29? I've edited the answer to show how you might add a legend in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.