python - 无法将字符串转换为浮点数:'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'
解决方案
'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()
然后你可以得到这样的 图片
推荐阅读
- nginx - Strapi 中的有效载荷太大
- c# - Caliburn.Micro Task.run() 阻塞 UI 线程
- nginx - Nginx 443 端口已经被它自己使用了?
- reactjs - 通过 React js 使用三元运算符进行具有 >2 条件的内联样式
- c++ - 使用半字节/亚 8 位值填充类似于 IP 标头的结构
- javascript - 如何在 svelte js 中突出显示活动的导航栏链接
- c# - 分配实体实例而不是实体 ID 创建新记录
- php - Laravel 中的模型可以应用多个查询吗?
- python - 为 Python 2.7 创建可执行文件
- ruby-on-rails - 具有特定 ID 的嵌套路由的 Rails 路由别名