Search code examples
pythonmatplotlibline-plotx-axisxticks

Setting xlim() removes the xticks


I am trying to plot 3 lines in matplotlib but whenever I add the xlim([]) the line disappears.

Without xlim:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D 

df.iloc[3:6,5:].T.plot()

enter image description here

with xlim:

df.iloc[3:6,5:].T.plot()
plt.xlim([410,1004])

enter image description here

I have made sure that the column I plot are astype float, so what could be the reason for this?


Solution

  • I found the problem: the labels of the X axis were string.

    I have changed them using the following finction from here: Python - How to convert only numbers in a mixed list into float?

    cols=df.columns.tolist()
    
    def maybe_float(s):
        try:
            return float(s)
        except (ValueError, TypeError):
            return s
    cols1=[maybe_float(v) for v in cols]
    df.columns=cols1
    
    

    After that it worked