首页 > 解决方案 > 如何将日期时间设置为 zaxis 而不会出错:OverflowError: Python int too large to convert to C long for 3D plot

问题描述

我正在尝试绘制 z 为时间的 3D 图像。当我尝试将 zaxis 标签设置为年,月时,我收到一个错误。

为了这:

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'))

我收到了这个错误:


OverflowError: Python int too large to convert to C long

<Figure size 432x288 with 1 Axes>

如果没有设置 zaxis 代码,我会得到这个图像:

在此处输入图像描述

提前致谢!!!

在此处输入图像描述

在“基准”的底部:

Name: Datum, Length: 81, dtype: object

标签: pythondatetimemplot3d

解决方案


发生溢出错误是因为 Matplotlib 的 DateFormatter 无法np.datetime64直接绘制数据,您的数据应该是这种情况。您需要将日期显式转换为datetime.date对象。

请看看这个: https ://matplotlib.org/3.1.1/gallery/recipes/common_date_problems.html

发生溢出错误是因为 Matplotlib 的 DateFormatter 无法np.datetime64直接绘制数据,您的数据应该是这种情况。您需要将日期显式转换为datetime.date对象。

请看看这个: https ://matplotlib.org/3.1.1/gallery/recipes/common_date_problems.html

编辑:这可能对你有用。

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()

输出:https ://imgur.com/a/WXM07it.jpg


推荐阅读