简体   繁体   中英

Matplotlib .fill_between() Offset By -1

I'm a newbie and trying to .fill_between() two lines on my chart. I've tried everything I can think of to ensure the underlying data is correct, but every time I chart this the .fill_between() appears one value on the x-axis short than what it should be. Here's my code:

df_combo = pd.read_csv('MySampleData.csv')
max_hist_temps = df_combo['hist_max']
min_hist_temps = df_combo['hist_min']
plt.figure()
plt.plot(max_hist_temps, '-.r'
        , min_hist_temps, '-.b'
        )
plt.gca().fill_between(range(len(max_hist_temps)),
        min_hist_temps, max_hist_temps,
        facecolor='blue',
        alpha = 0.25)
ax = plt.gca()
ax.axis([0,364,-45,45])
plt.show()

And here's some sample data:

Day_of_Year hist_min    hist_max
1                -16    15.6
2               -26.7   13.9
3               -26.7   13.3
4               -26.1   10.6
5                -15    12.8
6                -26.6  18.9
7               -30.6   21.7
8               -29.4   19.4
9               -27.8   17.8

Thank you for your help, Me

The problem is that you are not specifying properly the x parameter of fill_between . You are passing range(len(...)) which starts from 0, while your Day_of_Year starts from one, hence the 1-offset.

[Plus, I think your example is not complete as you should say that you set Day_of_Year as index of your data.]

To fix your problem, pass the index of max_hist_temp as x param in the fill_between function:

plt.gca().fill_between(max_hist_temps.index,   # CHANGED HERE
        min_hist_temps, max_hist_temps,
        facecolor='blue',
        alpha = 0.25)

You may want to use the Day_of_Year column of the dataframe as the actual x values, instead of some other index.

import io
import pandas as pd
import matplotlib.pyplot as plt

u = u"""Day_of_Year hist_min    hist_max
1                -16    15.6
2               -26.7   13.9
3               -26.7   13.3
4               -26.1   10.6
5                -15    12.8
6                -26.6  18.9
7               -30.6   21.7
8               -29.4   19.4
9               -27.8   17.8"""



df_combo = pd.read_csv(io.StringIO(u), delim_whitespace=True)
max_hist_temps = df_combo['hist_max']
min_hist_temps = df_combo['hist_min']
plt.figure()
plt.plot(df_combo['Day_of_Year'], max_hist_temps, '-.r',
         df_combo['Day_of_Year'], min_hist_temps, '-.b'
        )
plt.gca().fill_between(df_combo['Day_of_Year'],
        min_hist_temps, max_hist_temps,
        facecolor='blue',
        alpha = 0.25)
ax = plt.gca()
ax.axis([0,10,-45,45])
plt.show()

在此输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM