How to set datetime as zaxis without error: OverflowError: Python int too large to convert to C long for 3D plot

Viewed 307

I am trying to plot a 3D image where z is time. When I try to set the zaxis label to Year, month I receive an error.

For this:

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.scatter3D(df85['Messwert'], df85['average_cux'], df85['Datum'],c=df85['code'], cmap="jet_r")
ax.zaxis.set_major_formatter(dates.DateFormatter('%Y-%M'))

I got this error:


OverflowError: Python int too large to convert to C long

<Figure size 432x288 with 1 Axes>

Without the set zaxis code I get this image:

enter image description here

Thanks in advance!!!

enter image description here

at bottom of 'Datum':

Name: Datum, Length: 81, dtype: object
1 Answers

The overflow error occurs because Matplotlib's DateFormatter fails to plot np.datetime64 data directly, which should be the case with your data. You need to explicitly convert your dates to datetime.date objects.

Please have a look at this : https://matplotlib.org/3.1.1/gallery/recipes/common_date_problems.html

The overflow error occurs because Matplotlib's DateFormatter fails to plot np.datetime64 data directly, which should be the case with your data. You need to explicitly convert your dates to datetime.date objects.

Please have a look at this : https://matplotlib.org/3.1.1/gallery/recipes/common_date_problems.html

Edit : This might be useful to you.

import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib.dates import date2num, DateFormatter
import numpy as np
import pandas as pd
from mpl_toolkits.mplot3d import Axes3D
from datetime import datetime, timedelta

# a test dataframe
df = pd.DataFrame({
    'date': np.array([str(datetime(2020,3,30).date()+timedelta(x+1))+' 00:00:00' for x in range(200)], dtype='object'),
    'sales': np.random.randint(low=1, high=200, size=200),
    '%sales in US' : 30 * np.random.random_sample(size=200) + 20
})

# appropriate type conversions
df['date']= pd.to_datetime(df['date'])
df['date'] = df['date'].apply(date2num)

fig = plt.figure()
ax = plt.axes(projection='3d')
ax.scatter3D(df['sales'], df['%sales in US'], df['date'], c=df['date'], cmap="jet_r")
ax.zaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y-%M'))
plt.xlabel('sales', fontsize=20)
plt.ylabel('%sales in US', fontsize=16)
ax.set_zlabel('date', fontsize=16) 
plt.show()

Output : https://imgur.com/a/WXM07it.jpg

Related