I am a new to Python and currently trying to plot the data in dataframe with barchart and line.
[Environment]
OS: Windows 7 - 64bit
Visual Studio Code 1.45.1
Python 2020.6.91350
The following is the base data in csv format and it is read by the code below.
[testData.csv]
year,ordered,sold,YoY-ordered,YoY-sold
2015,100,80,0.1,-0.05
2016,120,100,0.2,0.25
2017,100,130,-0.166666667,0.3
2018,80,90,-0.2,-0.307692308
2019,90,95,0.125,0.055555556
2020,100,90,0.111111111,-0.052631579
[code.py]
import matplotlib as mplt
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
df = pd.read_csv('./testData.csv')
df=df.set_index("year")
idxO = "ordered"
idxS = "sold"
idxOYoY = "YoY-ordered"
idxSYoY = "YoY-sold"
fig = plt.figure(figsize=(12,5))
fig.suptitle("title")
ax1 = fig.add_subplot()
ax2 = ax1.twinx()
ax1.set_ylabel("Ordered, Sold")
ax2.set_ylabel("YoY")
df[[idxO, idxS]].plot(ax=ax1,kind="bar", color=["black","gray"])
df[[idxOYoY, idxSYoY]].plot(ax=ax2,kind="line", marker="o", color=["blue","lightblue"])
handler1, label1 = ax1.get_legend_handles_labels()
handler2, label2 = ax2.get_legend_handles_labels()
ax1.legend(handler1 + handler2, label1 + label2)
ax2.get_legend().remove()
plt.show()
It gives the graph below.

I found that I can get the graph I want, except the values of x-axis, if I do not set year as the index of the dataframe (commented out df=df.set_index("year")).

What I want to do is create the plot with the correct index (year) for x-axis.


