0

Hey I have issue with the matplotlib twinx axes, I have 2 plot with the same X ticks, But when I set them both in the same plot with twinx I get wrong plot.

  • The first plot data:

    Potential_Date_month
    1     0.033616
    2     0.033256
    3     0.026578
    4     0.029624
    5     0.026549
    6     0.029654
    7     0.031489
    8     0.025707
    9     0.030870
    10    0.023068
    11    0.042049
    12    0.056363
    Name: target, dtype: int64
    
    
    

and plot looks:

enter image description here

  • The secand plot data:

    Potential_Date_month
    1      7318
    2      6886
    3     18737
    4     11342
    5     19624
    6     22324
    7     18451
    8     15988
    9      5928
    10     5462
    11    10250
    12     5571
    Name: target, dtype: int64```
    
    
    

enter image description here

But when I use the next code, something get wrong:

    fig,ax1 = plt.subplots()
    ax2 = ax1.twinx()

    series1.plot(ax = ax1,color = 'blue')
    series2.plot.bar(ax = ax2, color = 'green', alpha = 0.5)

    plt.show()

plot:

s

you can see the line plot isn't staring from one ticks, it start with 2. I'm not sure what cause this issue,

Thank you.

Yair hadad
  • 437
  • 3
  • 17
  • 1
    Pandas' bar plots are automatically made "categorical", setting the first bar at internal position "0", the second at "1", ... and then labeling the bars with the values from the index. The lineplot, however, will use the numeric values. Often a simple trick is to make the index column categorical. – JohanC Jan 01 '22 at 19:50
  • You can use `ax1.plot(range(len(series1)), series1, color='blue')` to create the lineplot via matplotlib, using the same x-positions as the bar plot. – JohanC Jan 01 '22 at 19:58

0 Answers0