首页 > 解决方案 > 无法将字符串转换为浮点数:'12-31'

问题描述

我需要绘制每天最低和最高温度的两条线

我的数据框如下所示:

 Date  min  max  min2015  max2015
0    01-01 -160  156     -133       11
1    01-02 -267  139     -122       39
2    01-03 -267  133      -67       39
3    01-04 -261  106      -88       44

我只用日期和月份格式化的日期列,而不是年份,原因是它是 2004-2014 之间温度的混合和混合,这就是为什么不存在年份的原因。

所以我试着像这样绘制:

 fig, ax = plt.subplots(figsize=(10, 6))
    axb = ax.twinx()

    # Same as above
    ax.set_xlabel('Date')
    ax.set_ylabel('Temp')
    ax.set_title('Min and Max temperature 2004-2014')
    ax.grid(True)

    # Plotting on the first y-axis
    ax.plot(new_df.Date, new_df['min'], color='tab:orange', label='Min')
    ax.plot(new_df.Date, new_df['max'], color='tab:olive', label='Max')

但我明白了:

ValueError: could not convert string to float: '12-31'

标签: pythonpython-3.xpandasdataframematplotlib

解决方案


'plot' 函数不能识别字符串类型,你可以使用 'plot_date' 函数代替。

plt.xlabel('Date')
plt.ylabel('Temp')
plt.title('Min and Max temperature 2004-2014')
plt.grid(True)

plt.plot_date(['01-01', '01-02', '01-03'], [13, 15, 12], color='tab:orange', label='Min')
plt.show()

然后你可以得到这样的 图片


推荐阅读