R-ggplot的奇数行为。堆积面积图显示不正确

时间:2018-11-05 21:48:50

标签: r ggplot2

我在R中使用ggplot和geom_area时遇到问题。我的意图是生成一个堆积的面积图,像这样一个x轴上的时间和y轴上的p_gen值(用具有相同数据的Excel制作) ):

示例堆积面积图:

img

我尝试使用下面显示的代码绘制图形:

ggplot(pcpcen, aes(x=datetime, y=p_gen, fill = type)) + geom_area()

pcpcen 与此数据帧相对应的位置(不是所有数据都包含,而是相同的结构)

week,datetime,type,p_gen,is_ernc
376,2025-12-13 11:00:00,BESS,0.1,1
376,2025-12-13 11:00:00,BIO,302.49999999999994,1
376,2025-12-13 11:00:00,BOMBEO,0.0,1
376,2025-12-13 11:00:00,CARBON,2830.7999999999997,1
376,2025-12-13 11:00:00,COG,117.00000000000001,1
376,2025-12-13 11:00:00,DIESEL,0.0,1
376,2025-12-13 11:00:00,DIESEL_CC,0.0,1
376,2025-12-13 11:00:00,EOL,528.7,1
376,2025-12-13 11:00:00,GEO,48.0,1
376,2025-12-13 11:00:00,GLP,0.0,1
376,2025-12-13 11:00:00,GNL_CA,250.5,1
376,2025-12-13 11:00:00,GNL_CC,658.0,1
376,2025-12-13 11:00:00,HIDRO,2274.399999999999,1
376,2025-12-13 11:00:00,HIDRO_EMB,2352.2,0
376,2025-12-13 11:00:00,HIDRO_MINI,24.400000000000002,0
376,2025-12-13 11:00:00,SOL_CSP,31.5,1
376,2025-12-13 11:00:00,SOL_FV,2155.5,1
347,2025-05-22 10:00:00,BESS,0.1,1
347,2025-05-22 10:00:00,BIO,390.29999999999995,1
347,2025-05-22 10:00:00,BOMBEO,0.0,1
347,2025-05-22 10:00:00,CARBON,3865.5999999999995,1
347,2025-05-22 10:00:00,COG,117.00000000000001,1
347,2025-05-22 10:00:00,DIESEL,0.0,1
347,2025-05-22 10:00:00,DIESEL_CC,0.0,1
347,2025-05-22 10:00:00,EOL,862.8000000000001,1
347,2025-05-22 10:00:00,GEO,0.0,1
347,2025-05-22 10:00:00,GLP,37.0,1
347,2025-05-22 10:00:00,GNL_CA,255.1,1
347,2025-05-22 10:00:00,GNL_CC,1775.6,1
347,2025-05-22 10:00:00,HIDRO,1763.4000000000003,1
347,2025-05-22 10:00:00,HIDRO_EMB,2119.8999999999996,0
347,2025-05-22 10:00:00,HIDRO_MINI,25.000000000000004,0
347,2025-05-22 10:00:00,SOL_CSP,31.5,1
347,2025-05-22 10:00:00,SOL_FV,1501.1999999999991,1

但是在运行命令后,生成的图不是我期望的

R output chart

如果我将x轴更改为“周”列,则输出甚至更奇怪:

enter image description here

我在Windows 10 x64计算机上使用RStudio,这是版本的输出:

platform       x86_64-w64-mingw32          
arch           x86_64                      
os             mingw32                     
system         x86_64, mingw32             
status                                     
major          3                           
minor          5.1                         
year           2018                        
month          07                          
day            02                          
svn rev        74947                       
language       R                           
version.string R version 3.5.1 (2018-07-02)
nickname       Feather Spray

1 个答案:

答案 0 :(得分:0)

datetime设置为日期,和/或不要在导入数据时对要素进行不必要的设置。

library(ggplot2)
pcpcen <- read.csv("df.txt", sep = ",", stringsAsFactors = FALSE)
pcpcen$datetime <- as.Date(pcpcen$datetime, "%Y-%m-%d")
str(pcpcen)
ggplot(pcpcen) + geom_area(aes(x=datetime, y=p_gen, color = type, fill = type), position = "stack") + scale_x_date(labels = date_format("%Y-%m-%d"))
ggplot(pcpcen) + geom_area(aes(x=week, y=p_gen, fill = type))