pandas 数据框创建的图形的两条线之间的不同颜色阴影

Shading by different colors between two lines of a graph created by pandas data frame

我正在尝试在图表的线条之间添加阴影。我尝试使用 plt.fill_between() 但它不起作用。这是我的代码供您参考。请注意,如图所示,我想在绿色和橙色线条之间添加阴影。

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()

这是程序的输出,

您还必须将索引 (m1_t.index) 作为第一个参数传递给:

plt.fill_between(m1_t.index, m1_t['B'],m1_t['C'], interpolate=True, color='grey', alpha=0.5)

完整代码:

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()