man0s
man0s

Reputation: 58

Trying to find a graph in matplotlib

I have data that show the difference of temperatures from 1955 to 2020 from an average. I want to make a graph in matplotlib that looks like this: It shows temperature differences.

My data look like this:

DATE    TAVG
0   1955-06-01  NaN
1   1955-06-02  NaN
2   1955-06-03  NaN
3   1955-06-04  NaN
4   1955-06-05  NaN
... ... ...
5805    2020-08-27  2.067854
5806    2020-08-28  3.267854
5807    2020-08-29  3.067854
5808    2020-08-30  1.567854
5809    2020-08-31  4.167854

I can't find the right graph, could you help me? If it is from another library, there is no problem.

Upvotes: 0

Views: 55

Answers (1)

TomasO
TomasO

Reputation: 183

You can use the pandas plotting (basicly, it's matplotlib). For the plot, I just created some fake data. I also assumed the line plot is a moving average.

import random
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import seaborn as sns

# Create fake data
cols=['DATE','TAVG']
numdays = 92
date_list =  pd.date_range(start='1/1/2022', periods=numdays, freq='D').astype('str').tolist()
tavg_list = [round(random.uniform(-3.33, 3.33), 2) for i in range(numdays)]
df = pd.DataFrame({"DATE": date_list, "TAVG": tavg_list})

# line plot based on moving average
ma_days = 10  # number of days for moving average

# use seaborn styling on plot
sns.set()
sns.set_context("notebook")    # options: paper, notebook, talk, poster
sns.set_style("darkgrid", {"axes.facecolor":"0.9",'font.family':['Roboto']})

# tuple with size of plot (W,H)
pltsize = (10,7)

# plot bars from the dataframe
ax = df.plot(x='DATE', y='TAVG', kind='bar', legend=False, figsize=pltsize,
             color=(df['TAVG'] > 0).map({True:'darkorange', False:'royalblue'}))

# calc moving average and save to df.
df['MA'] = df.rolling(window=ma_days).mean()

# plot line chart on same bar chart
df.plot(ax=ax, x='DATE', y='MA', kind='line', legend=False, figsize=pltsize,
        color='black', lw=1)

# change x-axis labels to only so monthly
ax.xaxis.set_major_locator(mdates.MonthLocator())

plt.show()

Output:

TemperaturePlot

Upvotes: 1

Related Questions