Search code examples
pythonmatplotlibgraph

Matplotlib line graph background colouring misaligned


I currently have a line graph that plots a data column and I want to colour the background based on the number of another data column. This is how it's looking at the moment, the colour is ok but it's not lining up properly to the data: Line graph with misaligned colours

This is my dataframe:

                               Scores  Moods
Times
2022-12-05 08:25:19.618648       3      1
2022-12-05 08:37:47.121735       2      2
2022-12-05 09:25:13.647687       2      21 

My current code:

df = pd.DataFrame({"Times": times})
df["Scores"] = scores
df["Moods"] = moods
df = df.set_index("Times")
plt.plot(df["Scores"])
ax: axis.Axis.axes =plt.gca()
ax.pcolorfast(ax.get_xlim(),ax.get_ylim(),df["Moods"].values[np.newaxis],cmap="RdYlGn",alpha=0.4)
            
days = mdates.DayLocator()
days_fmt = mdates.DateFormatter('%D')
ax.xaxis.set_major_locator(days)
ax.xaxis.set_major_formatter(days_fmt)
ax.margins(0)
            
#set plot title
plt.title("Mental workload for this week")
plt.xlabel("Time")
plt.ylabel("Mental workload")
plt.ylim(1,5)


plt.savefig('images/mwltrend.png', bbox_inches='tight')
plt.close()

I've seen someone who has the same problem: How to change pyplot background colour in region of interest? but for some reason the code doesn't work when I try to do their implementation:

ax.pcolor(df.index,ax.get_ylim(),df["Moods"].values[np.newaxis],cmap="RdYlGn",alpha=0.4)

I'm getting this error:

nextcord.errors.ApplicationInvokeError: Command raised an exception: TypeError: Dimensions of C (1, 3) are incompatible with X (3) and/or Y (2); see help(pcolor) 

Any ways to get my desired effect?


Solution

  • Managed to get it working by instead of using df["Moods"].values[np.newaxis] I used np.tile(df["Moods"].values,(2,1)) to instead duplicate the array twice for both y bounds. Result now looks like this, which is pretty much exactly what I wanted:

    Accurate colouring graph