Home > database >  How to show the Year data in the horizontal lines of 2 plots?
How to show the Year data in the horizontal lines of 2 plots?

Time:05-18

I have a question regarding the plots. I have a dataframe named log_return_data. Here is the snapshot of the dataframe :

enter image description here

I want to plot 3 plots of each returns in 1 plots and the corresponding time ( in column Index). Here is the code I wrote:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt


fig1, axis = plt.subplots(3,1,figsize=(9,6),dpi=100)

log_return_data['HPQ_Returns'][1377:].plot(ax=axis[0], title='HPQ', fontsize=8, sharex=True, linewidth=0.6)
log_return_data['MSFT_Returns'][1377:].plot(ax=axis[1], title='MSFT', fontsize=8,sharex=True, linewidth=0.6)
log_return_data['INTC_Returns'][1377:].plot(ax=axis[2], title='INTC', fontsize=8,sharex=True, linewidth=0.6)

plt.savefig('returns')

And this is the result :

enter image description here

However, I want the Year Data is not only in the last plot ( of INTC data) but also in the HPQ and MSFT ( 2 first plots). Is there anyway solving this problem ? Thanks.

##Edit : With the help of the 1st answerer, I change to code to :

log_return_data['HPQ_Returns'][1377:].plot(ax=axis[0], title='HPQ', fontsize=8, linewidth=0.6)

And this is the result : enter image description here

How can I remove 3 title 'Date' in x-axis of each plot ?

CodePudding user response:

Since the time index is the same for all three plot, you can use sharex=False in all three plot calls (which is the default) and you should get all the xticks and still have the plots aligned correctly:

log_return_data['HPQ_Returns'][1377:].plot(ax=axis[0], title='HPQ', fontsize=8, sharex=False, linewidth=0.6)
log_return_data['MSFT_Returns'][1377:].plot(ax=axis[1], title='MSFT', fontsize=8,sharex=False, linewidth=0.6)
log_return_data['INTC_Returns'][1377:].plot(ax=axis[2], title='INTC', fontsize=8,sharex=False, linewidth=0.6)

sharex=True would generate a different alignment of the plots when you have different series with different time indices not perfectly aligning, but it's not your case.

Edit after comments:

Since now the titles overlap with both the axis label and the axis tick labels, you can try the following before plt.savefig():

# This removes the 'Date' label from every axis except the last.
for ax in axis[:-1]:
    ax.set_xlabel('')

# This rearranges the layout (the title still would overlap with the tick labels).
plt.tight_layout()

  • Related