Vincent
Vincent

Reputation: 229

How to add colors in stacked area chart

pls I need to add a area color to my code to show a plot similar to this one bellow:

enter image description here

My code is here:

import numpy as np
import pandas as pd
from pandas import DataFrame
import matplotlib.pyplot as plt
from matplotlib import pyplot as plt

 df = pd.DataFrame({'Time': [1,2,3,4,5],
       'T=0': [0.5,0.16,0,0.25,0],
        'T=2': [0.5,0.5,1,1,1],
        'T=10': [0.75,0.8,0.85,0.9,0.8]
        })

  plt.plot( 'Time', 'T=10', data=df, marker='d', color='black', markersize=5,      linewidth=1.5, linestyle=':')

  plt.plot( 'Time', 'T=2', data=df, marker='^', color='black', markersize=4,   linewidth=1.5,linestyle='--')
  plt.plot( 'Time', 'T=0', data=df, marker='o', color='black', markersize=4, linewidth=1.5,linestyle='-')

  plt.legend()

  plt.xlabel("Time")
  plt.xticks([1,2,3,4,5])
  plt.xlim(0.9, 5.02)
  plt.ylabel("Average")
  plt.ylim(0, 1.02)
  plt.show()

The actual result: enter image description here Many thanks.

Upvotes: 0

Views: 140

Answers (1)

pakpe
pakpe

Reputation: 5479

All you need to do is add the following 3 lines to your code:

plt.fill_between(df['Time'], df['T=0'], alpha = 0.3, color = 'steelblue')
plt.fill_between(df['Time'], df['T=0'], df['T=2'], alpha = 0.3, color = 'yellow')
plt.fill_between(df['Time'], df['T=2'], df['T=10'], alpha = 0.3, color = 'red')

enter image description here

You can also create a legend corresponding to the colors. However, in the case of your graph, since two plot lines cross, it is best to leave the legend assigned to the plot lines rather than the colors (as you have).

Upvotes: 1

Related Questions