multiple xticks stacking when using twinx

56 Views Asked by At

I have a series that looks like this:

2022-10-08    0.357143
2022-10-09    0.500000
2022-10-10    0.500000
2022-10-11    0.500000
2022-10-12    0.642857
                ...   
2022-12-26    1.792857
2022-12-27    1.757143
2022-12-28    1.807143
2022-12-29    2.092857
2022-12-30    1.785714
Name: amount, Length: 84, dtype: float64

I basically wanted to plot it with 2 y axes with a different scale for each.

This is my code for plotting this data with 2 y axes, the one on the left showing the amount as is, and the one on the right showing it multiplied by 7 (7 day mean and sum)

#plot 7 day rolling average
weekly.plot()
# Create a second y-axis to show total weekly hours
y2 = plt.twinx()
# plot the summation of a 7 day window
y2.plot(weekly*7)

but it shows the plot like this with overlapping xtick labels

result plot

Note: if I drop a row from the middle of the series, the problem does not persist.

weekly.drop(index="2022-10-12",inplace=True)
#plot 7 day rolling average
weekly.plot()
# Create a second y-axis to show total weekly hours
y2 = plt.twinx()
# plot the summation of a 7 day window
y2.plot(weekly*7)

result plot

how do I solve this problem? And, is there a better way to achieve the same plot?

1

There are 1 best solutions below

0
On

I was able to figure it out!

#plot 7 day rolling average
weekly.plot()
# Create a second y-axis to show total weekly hours
y2 = plt.twinx()
# plot the summation of a 7 day window
y2.plot((weekly*7).values)

code result