繁体   English   中英

geom_bar无效的y.axis值R

[英]geom_bar invalid y.axis values R

我有以下数据框:

> str(drivePerTaskMelted)
'data.frame':   10508 obs. of  4 variables:
 $ CSS_WEEK_END_DATE: Date, format: "2012-01-13" "2012-01-20" "2012-01-27" "2012-02-03" ...
 $ patch            : Factor w/ 71 levels "BV","BVG","BVH",..: 1 1 1 1 1 1 1 1 1 1 ...
 $ Drive.Per.Task   : num  28 28.8 28.2 28.1 27.9 26.4 26.6 26.6 26.6 26.7 ...
 $ Months           : chr  "January" "January" "January" "February" ...

我正在尝试绘制条形图:

ggplot(drivePerTaskMelted[patch==c("BVG1","BVG2","BVG3","BVG4"),],
aes(x=patch, y=Drive.Per.Task,fill=patch)) + 
geom_bar(stat="identity") + 
geom_text(aes(label = max(Drive.Per.Task, na.rm = TRUE)))

这将绘制以下图:

在此处输入图片说明

我已经使用过stat="identity"但是它仍然没有按原样使用y.values。 y值例如28、28.2等。此外,我正在尝试在每个栏的顶部标记最大y.axis值。 但是它在底部以奇怪的方式显示了35.2。

例如:BVG1的摘要是:

> summary(drivePerTaskMelted[patch=="BVG1",])
 CSS_WEEK_END_DATE        patch     Drive.Per.Task     Months         
 Min.   :2012-01-13   BVG1   :148   Min.   :22.60   Length:148        
 1st Qu.:2012-09-26   BV     :  0   1st Qu.:28.38   Class :character  
 Median :2013-06-10   BVG    :  0   Median :30.20   Mode  :character  
 Mean   :2013-06-10   BVH    :  0   Mean   :30.08                     
 3rd Qu.:2014-02-22   BVG2   :  0   3rd Qu.:31.70                     
 Max.   :2014-11-07   BVG3   :  0   Max.   :35.90                     
                      (Other):  0                        

在这里谢谢

这很可能会产生您想要的结果,但是如果没有数据集就无法进行测试。 这将为每个patch创建平均Drive.Per.Task ,并在Drive.Per.Task上方显示最大Drive.Per.Task

# not tested
library(ggplot2)
labs <- function(x) data.frame(y=mean(x)+0.2,label=round(max(x),2))
ggplot(drivePerTaskMelted[patch %in% c("BVG1","BVG2","BVG3","BVG4"),],
       aes(x=patch, y=Drive.Per.Task,fill=patch)) + 
  stat_summary(fun.y=mean,geom="bar")+
  stat_summary(fun.data=labs,geom="text")

假定在数据帧drivePerTaskMelted之外定义了一个矢量patch

另外,请注意, patch %in% c("BVG1","BVG2","BVG3","BVG4") patch==c("BVG1","BVG2","BVG3","BVG4") 前者是提取包含BVG1-4的行的正确方法。

这是使用内置mtcars数据集的工作示例。

# use built-in mtcars dataset for demonstration
df <- mtcars
df$cyl <- as.factor(df$cyl)   # number of cylinders to factor

labs <- function(x) data.frame(y=mean(x)+0.2,label=round(max(x),2))
library(ggplot2)
ggplot(df,aes(x=cyl,y=wt,fill=cyl))+
  stat_summary(fun.y=mean,geom="bar")+
  stat_summary(fun.data=labs,geom="text")

我的猜测是,有许多CSS_WEEK_END_DATE列,并且您看到的总和。 您正在查看特定日期吗? 您可以运行以下命令,看看现在的柱线/值是否更好?

ggplot(drivePerTaskMelted[patch %in% c("BVG1","BVG2","BVG3","BVG4"),],aes(x=patch, y=Drive.Per.Task,fill=patch)) + 
geom_bar(stat="identity") + 
geom_text(aes(label = max(Drive.Per.Task, na.rm = TRUE)))+
facet_wrap(~ CSS_WEEK_END_DATE))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM