1

我正在尝试使用geom_col为时间序列(年度和季度)中的值绘制列。

当我使用Zoo包的 YearQtr 数据类型作为 x 轴值并将 y 轴值四舍五入为整数时,geom_col 似乎没有使用默认的 postion = 'identity'来确定基于 y 值的列栏高度每次出现。相反,它似乎切换到position = 'count'并将舍入的 y 值视为因子,计算每个因子值的出现次数(例如,3 次出现的舍入 y 值 = 11)

如果我切换到 geom_line,则该图适用于每季度的 x 轴值和四舍五入的 y 轴值。

library(zoo)
library(ggplot2)

Annual.Periods <- seq(to = 2020, by = 1, length.out = 8) # 8 years
Quarter.Periods <- as.yearqtr(seq(to = 2020, by = 0.25, length.out = 8)) # 8 Quarters

Values <- seq(to = 11, by = 0.25, length.out = 8)

Data.Annual.Real <- data.frame(X = Annual.Periods, Y = round(Values, 1))
Data.Annual.Whole <- data.frame(X = Annual.Periods, Y = round(Values, 0))
Data.Quarter.Real <- data.frame(X = Quarter.Periods, Y = round(Values, 1))
Data.Quarter.Whole <- data.frame(X = Quarter.Periods, Y = round(Values, 0))

ggplot(data = Data.Annual.Real, aes(X, Y)) + geom_col()
ggplot(data = Data.Annual.Whole, aes(X, Y)) + geom_col()
ggplot(data = Data.Quarter.Real, aes(X, Y)) + geom_col()
ggplot(data = Data.Quarter.Whole, aes(X, Y)) + geom_col() # appears to treat y-values as factors and uses position = 'count' to count occurrences (e.g., 3 occurrences have a rounded Value = 11)

ggplot(data = Data.Quarter.Whole, aes(X, Y)) + geom_line() 

rstudioapi::versionInfo()
# $mode
# [1] "desktop"
# 
# $version
# [1] ‘1.3.959’
# 
# $release_name
# [1] "Middlemist Red"

sessionInfo()
# R version 4.0.0 (2020-04-24)
# Platform: x86_64-apple-darwin17.0 (64-bit)
# Running under: macOS Mojave 10.14.6
# 
# Matrix products: default
# BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
# LAPACK: /Library/Frameworks/R.framework/Versions/4.0/Resources/lib/libRlapack.dylib
# 
# locale:
#   [1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
# 
# attached base packages:
#   [1] stats     graphics  grDevices utils     datasets  methods   base     
# 
# other attached packages:
#   [1] ggplot2_3.3.1 zoo_1.8-8 
4

1 回答 1

0

ggplot 试图猜测它的 -function 的方向geom_col(),这意味着哪个变量作为条形的基础,哪个作为要表示的值。显然,您的 - 变量中没有任何十进制数字,Y它选择它作为它的基础(尽管它保持数字,没有转换为因子),并总结了你的季度。

对于这种情况,您可以geom_col()通过参数提供信息用作条形基础的orientation=变量:

ggplot(data = Data.Quarter.Whole, aes(X, Y)) + geom_col(orientation = "x") 

编辑:我刚刚看到 Roman 在评论中回答了它。

在此处输入图像描述

于 2020-07-08T07:14:54.100 回答