I am trying to shading between the lines of a graph. I tried by using plt.fill_between() but it does not works. Here, are my code for your information. Please note that I want to shade between the green and orange color lines as shown in the image.
import matplotlib.pyplot as plt
import pandas as pd
m1_t = pd.DataFrame({
"A":[0.41,0.24,1.22,0.41,0.85,1.15,0.91,0.63,0.38,1.18],
"B":[13.41,18.33,23.69,12.68,24.71,16.0,20.11,21.43,26.58,17.71],
"C":[6.59,5.0,19.51,7.07,24.71,14.87,14.62,18.1,10.26,13.98,]
})
fig, ax = plt.subplots()
twin_x = ax.twinx() # Create a pseudo axes based off of the original
# Put the bar plot on the "primary y" via ax=ax
m1_t['A'].plot(kind='bar',colormap=cmap1, ax=ax, zorder=1,legend=True,figsize=(8,4), width=.55)
m1_t[['B','C']].plot(kind='line', color=['darkorange','green'], linewidth=3, ax=twin_x,marker='o' ,zorder=2,legend=True)
plt.fill_between(m1_t['B'],m1_t['C'], interpolate=True)
ax.grid(True, zorder=0)
ax.set_axisbelow(True)
ax.set_xticklabels(('P0', 'P1','P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'P9'),Rotation=360)
# X and Y axis label
ax.set_xlabel('Id',fontsize=12)
# ax.set_ylabel('Elergy Loss (kW)', color='g')
ax.set_ylabel('Ax1',fontsize=12)
twin_x.set_ylabel('Ax2',fontsize=12)
twin_x.set_ylim(0,50)
# Save the graph into a PDF file
fig = plt.gcf()
plt.show()
You also have to pass the index (m1_t.index
) as the first parameter with:
plt.fill_between(m1_t.index, m1_t['B'],m1_t['C'], interpolate=True, color='grey', alpha=0.5)
Full Code:
import matplotlib.pyplot as plt
import pandas as pd
m1_t = pd.DataFrame({
"A":[0.41,0.24,1.22,0.41,0.85,1.15,0.91,0.63,0.38,1.18],
"B":[13.41,18.33,23.69,12.68,24.71,16.0,20.11,21.43,26.58,17.71],
"C":[6.59,5.0,19.51,7.07,24.71,14.87,14.62,18.1,10.26,13.98,]
})
fig, ax = plt.subplots()
twin_x = ax.twinx() # Create a pseudo axes based off of the original
# Put the bar plot on the "primary y" via ax=ax
m1_t['A'].plot(kind='bar', ax=ax, zorder=1,legend=True,figsize=(8,4), width=.55)
m1_t[['B','C']].plot(kind='line', color=['darkorange','green'], linewidth=3, ax=twin_x,marker='o' ,zorder=2,legend=True)
plt.fill_between(m1_t.index, m1_t['B'],m1_t['C'], interpolate=True, color='grey', alpha=0.5)
ax.grid(True, zorder=0)
ax.set_axisbelow(True)
ax.set_xticklabels(('P0', 'P1','P2', 'P3', 'P4', 'P5', 'P6', 'P7', 'P8', 'P9'),Rotation=360)
# X and Y axis label
ax.set_xlabel('Id',fontsize=12)
# ax.set_ylabel('Elergy Loss (kW)', color='g')
ax.set_ylabel('Ax1',fontsize=12)
twin_x.set_ylabel('Ax2',fontsize=12)
twin_x.set_ylim(0,50)
# Save the graph into a PDF file
fig = plt.gcf()