首页 > 解决方案 > TypeError - 无法根据规则“安全”将数组数据从 dtype('O') 转换为 dtype('float64')

问题描述

我在同一轴上绘制了两个图,twinx()但输出不正确。这些图未相对于零轴对齐。我正在分享下面的情节。

Days percentage changefloattotal traded quantityinteger

fig = plt.figure()
ax1 = fig.add_subplot(1, 1, 1)
ax2 = ax1.twinx()

ax1.set_xlabel('Date')
ax2.set_ylabel('Total Traded Quantity', color='red')
ax2.plot(df['Total Traded Quantity'], 'r-')

ax1.plot(df['Day_Perc_Change'], 'b-')
ax1.set_ylabel('Day_Perc_Change', color='blue')


def align_yaxis(ax1, v1, ax2, v2):
    y1 = ax1.transData.transform((0, v1))
    y2 = ax2.transData.transform((0, v2))
    inv = ax2.transData.inverted()
    dy = inv.transform((0, 0)) - inv.transform((0, y1-y2))
    mini, maxi = ax2.get_ylim()
    ax2.set_ylim(mini+dy, maxi+dy)
align_yaxis(ax1, 0, ax2, 0)

我也得到一个typeError-Cannot cast array data from dtype('O') to dtype('float64') according to the rule 'safe'. 如果您可以修复它并对齐轴以进行正确的可视化,请提供帮助。

在此处输入图像描述

标签: matplotlibdata-visualizationtwinx

解决方案


推荐阅读