如何按年份或在同一图上显示多条线来将子图中的可视化分开?

如何解决如何按年份或在同一图上显示多条线来将子图中的可视化分开?

在问这个问题之前,我昨天花了一天的时间在以前的Stack Overflow答案以及Internet中寻找答案,但是我找不到解决问题的方法。

我有一个随着时间推移在美国石油生产的数据框架。数据包括日期列和相应的值。数据的最小可复制代码如下:

import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv('https://raw.githubusercontent.com/Arsik36/SO/master/Oil%20production.csv',parse_dates = ['date'],index_col = 'date')

我使用下面的代码来可视化一段时间内石油生产的总体趋势:

# Visualizing Time Series
df.value.plot(title = 'Oil production over time')

# Specifying naming convention for x-axis
plt.xlabel('Date')

# Specifying naming convention for y-axis
plt.ylabel('Oil production volume')

# Improving visual aesthetics
plt.tight_layout()

# Showing the result
plt.show()

通过在您的环境中运行此代码,您会看到该图显示了值随时间的分布。 我遇到的困难是要么按年份将图分成多个子图(例如1995年至1997年),要么每年在一张图上显示不同的线条

df['1995' : '1997'].value.plot(title = 'Oil production over time',subplots = True)

当我使用此代码时,它仅对1997年的数据进行了正确的子集划分,并且使用subplots = True该图确实是按年份分隔的。但是,通过在您的环境中运行它,您可以看到该图在x轴上按年分隔,但是利用1条线来显示所有3年的结果。我想做的是将一个地块分成1995、1996和1997年的3个子图,或者在一个图中显示3条线,每条线对应一个唯一的年份。

对于我来说,重要的是能够通过将日期列保留为索引列而不必创建任何其他列(如果可能)来解决此问题。

预先感谢您的帮助。

解决方法

您是正确的建议,没有针对python的已实现解决方案,我知道R在fpp2中对此具有实现。

我想出的解决方案是从您的数据中获取每年的数据,并将其连续绘制在for循环中。

years=[1995,1996,1997]

fig,ax=plt.subplots(figsize=(10,30))

for i in years:
    aux=df[df.index.map(lambda x : x.year == i)] #slice the data for each year
    aux.reset_index(inplace=True,drop=True) #we need to drop the index in order to be able to plot all lines in the same timeframe.

    #afterwards an index is given to all the series
    aux.set_index(pd.date_range(pd.to_datetime('01-01-2000'),periods=aux.shape[0],freq='W'),inplace=True)
    ax.set_xticklabels(aux.index,rotation = 90)
    ax.plot(aux.values,label=str(i))
    plt.legend()

fig.autofmt_xdate() #to be able to see the dates clearly

fig.show()

这会产生如下结果:

resulting plot

剩下要做的就是格式化x轴标签,以便仅显示月份。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 <select id="xxx"> SELECT di.id, di.name, di.work_type, di.updated... <where> <if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 <property name="dynamic.classpath" value="tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-