I want to plot multiple variables from a dataframe using matplotlib but the final plot looks so weird

Viewed 285

I have a dataframe containing stocks of multiple companies and a date column. I want to plot these stocks values on the y axis and date on the x axis in the same plot.

Each stock starts from a different value (for example amazon starts from $3103 whereas apple starts from $112)

When I do that my plot looks like this

plot image

Here's my plot code:

import matplotlib.pyplot as plt

%matplotlib inline
fig2 = plt.figure()
ax2 = fig2.add_subplot('111')
ax2.plot(plot_stocks['Amazon High'])
ax2.plot(plot_stocks['Apple High'])
ax2.plot(plot_stocks['Facebook High'])
ax2.plot(plot_stocks['Microsoft High'])

Here's a sample of the data:

Date  Amazon High  Apple High Facebook High Microsoft High
0  2020-12-04     $3198.21   $122.8608       $283.46        $215.38
1  2020-12-03     $3228.64     $123.78       $286.65      $216.3757
2  2020-12-02        $3232     $123.37       $291.78        $215.47
3  2020-12-01     $3248.95   $123.4693        $289.3        $217.32
4  2020-11-30     $3228.39     $120.97        $277.7        $214.76
5  2020-11-27     $3216.19     $117.49       $279.13        $216.27
6  2020-11-25        $3198     $116.75       $280.18        $215.29
7  2020-11-24     $3134.25     $115.85     $277.8199        $214.25
8  2020-11-23    $3139.745   $117.6202     $270.9471        $212.29
9  2020-11-20     $3132.89     $118.77          $273       $213.285

One thing i forgot to mention is that the High columns are string and I couldn't change them even after I did this:

plot_stocks['Amazon High'] = plot_stocks['Amazon High'].replace(r'$', '')
1 Answers

You can manipulate your data by creating a multi-index with pd.MultiIndex.from_tuples():

This makes the plot automatically give you the output you are looking for:

Pandas Setup:

plot_stocks['Date'] = pd.to_datetime(plot_stocks['Date'])
plot_stocks = plot_stocks.replace('\$', '', regex=True)
plot_stocks.iloc[:,1:] = plot_stocks.iloc[:,1:].astype(float)
plot_stocks = plot_stocks.set_index('Date')
plot_stocks.columns = pd.MultiIndex.from_tuples([(col.split()[1], col.split()[0])
                                        for col in plot_stocks.columns])
plot_stocks
Out[1]: 
                High                              
              Amazon     Apple  Facebook Microsoft
Date                                              
2020-12-04  3198.210  122.8608  283.4600  215.3800
2020-12-03  3228.640  123.7800  286.6500  216.3757
2020-12-02  3232.000  123.3700  291.7800  215.4700
2020-12-01  3248.950  123.4693  289.3000  217.3200
2020-11-30  3228.390  120.9700  277.7000  214.7600
2020-11-27  3216.190  117.4900  279.1300  216.2700
2020-11-25  3198.000  116.7500  280.1800  215.2900
2020-11-24  3134.250  115.8500  277.8199  214.2500
2020-11-23  3139.745  117.6202  270.9471  212.2900
2020-11-20  3132.890  118.7700  273.0000  213.2850

Matplotlib Code:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
company_list = [col[1] for col in plot_stocks.columns]
plot_stocks.plot(ax=ax, title=f'Daily Stock Prices ({(", ").join(company_list)})')
ax.legend(title='Companies', labels=company_list)
ax.set_ylabel('Stock Prices')
plt.show()

enter image description here

Related