brohjoe
brohjoe

Reputation: 934

Matplotlib v 3 Length mismatch ValueError: Expected axis has x elements, new values have x+1 elements

I'm using Matplotlib version 3.2.1 with Python 3.7 and pandas 1.0.3.

I'm using the following code which results in a length mismatch error:

import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mpl_dates
df_train = pd.read_csv('mydata.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5', 'col6']
df_train['date'] = pd.to_datetime(df_train['date'])
df_train.set_index(['date'])

x_value = df_train['date']
y_value = df_train['col4']
plt.plot_date(x_value, y_value, 'g')
plt.gcf().autofmt_xdate()
plt.show()

which results in the following error:

     File "C:\Users\brohj\anaconda3\lib\site-packages\pandas\core\internals\managers.py", line 178, in set_axis
    f"Length mismatch: Expected axis has {old_len} elements, new "
ValueError: Length mismatch: Expected axis has 6 elements, new values have 7 elements

(Note: There is no typo in the error message. Copied directly as is.)

What gives? Thanks in advance.

Upvotes: 1

Views: 148

Answers (1)

Quang Hoang
Quang Hoang

Reputation: 150735

The problem is these two lines:

df_train = pd.read_csv('mydata.csv', date_parser=True)
df_train.columns = ['date', 'col1', 'col2', 'col3', 'col4', 'col5', 'col6']

which I believe your data in csv does not have a name for index. You can do:

# read and parse index as date
df_train = pd.read_csv('mydata.csv', parse_dates=True, index_col=[0])

# rename column
df_train.columns = ['col1', 'col2', 'col3', 'col4', 'col5']

# rename index
df_train.index.name = 'date'

df_train.plot(y='col4', c='g')
plt.show()

Upvotes: 2

Related Questions