Bijay Regmi
Bijay Regmi

Reputation: 1288

Pandas DataFrame.plot not setting xlim and ylim properly

I am plotting a large dataset using dataframe.plot() in pandas. Dataset contains data in csv format. As per documentation, I specify xlim and ylim as arg in df.plot as follows:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv(myfile) #contains 2 columns, Time in ms and Voltage in mV
xlabel = "Time in ms"
ylabel = "Volate in mV"
xlim = [0,100]
ylim = [0,8]
df.plot(x = "Time", xlabel= xlabel, ylabel=ylabel, xlim = xlim, ylim = ylim, kind="line")
plt.show()

Now the axes take the xlim and ylim values accordingly but the figure does not scale to these values and plot shows some part of of graph but not the area defined by 'xlim' and 'ylim'.

Without xlim set:

Image without Xlim

with xlimset:

Figure with xlim

I expected to focus on the spike in figure. Do I have to "shuffle" the plot in some way? I have tried plt.autofocus but that ignores all xlim and ylim values and shows whole figure anyways.

My Dataframe looks something like (sample files here):

      Time          V
0      0.0 -78.947773
1      1.0 -79.182998
2      2.0 -79.382532
3      3.0 -79.551480
4      4.0 -79.694185
..     ...        ...
496  496.0 -80.434649
497  497.0 -80.435128
498  498.0 -80.435604
499  499.0 -80.436079
500  500.0 -80.436551

[501 rows x 2 columns]

Matplotlib Version : 3.4.1 and Pandas 1.2.3

Upvotes: 2

Views: 1948

Answers (1)

Bijay Regmi
Bijay Regmi

Reputation: 1288

This was a bug with pandas.DataFrame.plot(), after creating an issue on GitHub, we have identified the cause. df.plot() was accepting an array without proof checking the elements for float or int dtype. I have created a pull request to address the issue and should be fixed with v1.3.0.

Meanwhile if you are setting xlim or ylim, make sure each element in the range is in int or float type.

I was using argparse to get user data and collecting data as

parser = ArgumentParser()
parser.add_argument("-xlim", help="Limit for x-Axis, start and end separated by space.", nargs="+")
args = parser.parse_args()

which would create an array args.xlim with string values causing this bug. I wrote a function to proofcheck value as

def is_int(s):
     try:
        int(s)
        return True
     except ValueError:
        return False

def is_float(s):
     try:
        float(s)
        return True
     except ValueError:
        return False

def check_number(s):
    if is_int(s):
        return int(s)
    elif is_float(s):
        return float(s)
    else:
        raise ArgumentTypeError("not a valid int or float number.")

which I can bind to check user input in argparse as

parser.add_argument("-xlim", help="Limit for x-Axis, start and end separated by space.", nargs="+", type= check_number)

Upvotes: 2

Related Questions