0

I want to plot a graph using matplotlib in Google Colab. In general, the graph looks fine except that I couldn't add a label to the x- or y-axis. I added some extra steps in the plot, so I'm not sure if that's why the plot is not working properly.

Here is the code:

df = pd.read_csv('/content/drive/My Drive/data.csv', sep=',')
df['timestamp'] = pd.to_datetime(df['timestamp'])

start_date = pd.to_datetime('2020-02-01')
end_date = pd.to_datetime('2020-03-01')
df = df.loc[(df['timestamp'] > start_date) &
              (df['timestamp'] < end_date)]

ID = 3
df = df[df['id'] == ID]

df['Date'] = [datetime.datetime.date(d) for d in df['timestamp']] 

df.plot(x='timestamp', y='data', figsize=(10, 6),) 
plt.axhline(y=40, color='r', linestyle='-')
plt.axhline(y=25, color='b', linestyle='-')

df['top_lim'] = 40
df['bottom_lim'] = 25

plt.fill_between(df.index, df['bottom_lim'], df['data'],
                where=(df['data'] >= df['bottom_lim'])&(df['data'] <= df['top_lim']),
                facecolor='orange', alpha=0.3)

mask = (df['data'] <= df['top_lim'])&(df['data'] >= df['bottom_lim'])
plt.scatter(df.index[mask], df['data'][mask], marker='.', color='black')

cumulated_time = df.index[mask].diff().sum()
plt.title(f'Cumulative time in range = {cumulated_time}')
plt.ylabel('data', fontsize=18)
plt.legend(loc='best')
plt.show()

Here is what the graph looks like:

enter image description here It seems the x-label timestamp was already there initially, but not the y-label, and I couldn't change the x-label by inserting plt.xlabel('data', fontsize=18) as well.

I have tried out a few ways in other posts but nothing changed.

nilsinelabore
  • 4,143
  • 17
  • 65
  • 122
  • Does this answer your question? [Why is my xlabel cut off in my matplotlib plot?](https://stackoverflow.com/questions/6774086/why-is-my-xlabel-cut-off-in-my-matplotlib-plot) – Diziet Asahi Mar 05 '20 at 09:54
  • @DizietAsahi Thank you for sharing the link - I tried the methodbut unfortunately nothing happened – nilsinelabore Mar 05 '20 at 11:33

1 Answers1

1

I had the same problemam. maby you shuld try upgrade your libry

import matplotlib.pyplot as plt
!pip install --upgrade matplotlib

I hope it works