如何在Seaborn通过YearMonth订购X轴

如何解决如何在Seaborn通过YearMonth订购X轴

我使用http://archive.ics.uci.edu/ml/datasets/Air+quality的当前版本 我的问题是我想创建一个图,该图按绘制在多张图上的不同要素的每月汇总进行排序

X轴的年月创建

INPUT:
df['DateTime'] = df['Date'].astype(str) + ' ' + df['Time'].astype(str)
df['DateTime'] = pd.to_datetime(df['DateTime'],format='%m/%d/%Y %H:%M:%S')
print(df['DateTime'].iloc[:2])

OUTPUT:
0   2004-11-23 19:00:00
1   2004-11-23 20:00:00
Name: DateTime,dtype: datetime64[ns]



INPUT:
df['Date'] = pd.to_datetime(df['Date'].astype(str),format='%m/%d/%Y')

df['Year'] = df['DateTime'].map(lambda x: x.year)
print(df['Year'].iloc[:2])

OUTPUT:
0    2004
1    2004
Name: Year,dtype: int64



INPUT:
df['YearMonth'] = pd.to_datetime(df.DateTime).dt.to_period('m')
print(df['YearMonth'].iloc[:2])

OUTPUT:
0    2004-11
1    2004-11
Name: YearMonth,dtype: period[M]

目标project具有相同的结果,格式

我的绘图

plt.figure(figsize=(30,60))
#fig,axes = plt.subplots(1,1,figsize=(30,60),dpi=100)

gasList = ['CO_GT','C6H6_GT','Nox_GT','NO2_GT']
for i,col in enumerate(gasList,start=1):
    plt.subplot(len(showList),i)    
    sns.pointplot(x='YearMonth',y=col,hue='Year',data=df)
    plt.title(col,y=0.5,loc='right')
    #axes.set_xticks(year_month_day)
plt.show()

enter image description here

理想绘图

我正在尝试达到与projects相同的目的

enter image description here

试图解决该问题

  • 如果我只使用DateTime,它可以对日期进行排序,但这会使绘图变得人口稠密
  • 我具有与创建YearMonth相同的数据格式
<class 'pandas.core.frame.DataFrame'>
Int64Index: 9357 entries,0 to 9356
Data columns (total 17 columns):
 #   Column        Non-Null Count  Dtype         
---  ------        --------------  -----         
 0   Date          9357 non-null   datetime64[ns]
 1   Time          9357 non-null   object        
 2   CO_GT         9357 non-null   float64       
 3   PT08_S1_CO    9357 non-null   float64       
 4   C6H6_GT       9357 non-null   float64       
 5   PT08_S2_NMHC  9357 non-null   float64       
 6   Nox_GT        9357 non-null   float64       
 7   PT08_S3_Nox   9357 non-null   float64       
 8   NO2_GT        9357 non-null   float64       
 9   PT08_S4_NO2   9357 non-null   float64       
 10  PT08_S5_O3    9357 non-null   float64       
 11  T             9357 non-null   float64       
 12  RH            9357 non-null   float64       
 13  AH            9357 non-null   float64       
 14  DateTime      9357 non-null   datetime64[ns]
 15  Year          9357 non-null   int64         
 16  YearMonth     9357 non-null   period[M]     
dtypes: datetime64[ns](2),float64(12),int64(1),object(1),period[M](1)
memory usage: 1.3+ MB
  • 他的数据集的时间格式是我的时间格式是我的日期,但我又改回了与他相同的时间
  • 我尝试使用seaborn的order参数。它加载了很长时间,但没有任何回报。
col_one_list = df['YearMonth'].tolist()
plt.figure(figsize=(30,60))

gasList = ['CO_GT',data=df,order = col_one_list )
    plt.title(col,loc='right')

plt.show()
  • 我自己创建了一个uniq值列表,但该列表也崩溃了。输出:正确的YearMonth-s x轴刻度,正确绘制外部元素,但未绘制任何数据点。
plt.figure(figsize=(30,60))

col_two_list = ['2004-03','2004-04','2004-05','2004-06','2004-07','2004-08','2004-09','2004-10','2004-11','2004-12','2005-01','2005-02','2005-03','2005-04']

gasList = ['CO_GT',order = col_two_list )
    plt.title(col,loc='right')

plt.show()

解决方法

简短回答

生成 pointplot 时,传递 sorted DataFrame(通过 YearMonth ),并且打印输出应该如您所愿。

没有上述排序,图片就是您所展示的(错误)。

长答案

我准备了一个仅两列的测试输入文件,如下所示:

DateTime    CO_GT  C6H6_GT
2004-11-01  2.7    12.4
2004-12-01  2.6    10.6
2004-10-01  3.0    13.8
2005-01-01  2.0    9.0
2005-02-01  2.2    8.0
2004-03-01  2.2    10.0
2004-09-01  2.2    12.0
2005-03-01  2.0    8.6
2004-04-01  2.1    10.2
2004-05-01  1.95   10.5
2004-06-01  1.85   10.4
2004-07-01  1.7    10.5
2005-04-01  1.3    4.5
2004-08-01  1.4    6.8

然后我阅读了一下,将 DateTime 列转换为 datetime 类型(早 尽可能地,即在阅读时):

df = pd.read_fwf('Input.csv',widths=[12,7,7],parse_dates=[0])

第一步是创建“辅助”列:

df['Year'] = df.DateTime.dt.year
df['YearMonth'] = df.DateTime.dt.to_period('m')

要生成图片,我跑了:

gasList = ['CO_GT','C6H6_GT']
plt.figure(figsize=(14,8))
for i,col in enumerate(gasList,start=1):
    plt.subplot(len(gasList),1,i)    
    sns.pointplot(x='YearMonth',y=col,hue='Year',data=df.sort_values('DateTime'))
    plt.title(col,y=0.5,loc='right')
plt.show()

结果是:

enter image description here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 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时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;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,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;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[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 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 -&gt; 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(&quot;/hires&quot;) 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&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-