条形图中的x轴标签并扩展数据框

时间:2019-01-16 19:45:48

标签: r ggplot2 dplyr

我的数据

df <- structure(list(variable = c("main.tmin", "main.tmin", "main.tmin", 
                        "main.tmin", "main.tmin"), 
           coef = c(-23.28653023, 22.98726658, -55.1958095, -30.08524407, 
                    36.22033036), 
           acz = c(101L, 103L, 107L, 113L, 114L)), 
          class = "data.frame", row.names = c(NA, -5L))

library(ggplot2)

ggplot(df, aes(x = acz, y = coef)) + geom_bar(stat = "identity")  

我想做两件事:

首先,我想将df扩展为101:114的acz,以便 没有任何值的NA。像这样

final.df <- data.frame(variable = "main.tmin",
                   acz = 101:114, 
                  coef = c(-23.28653, NA, 22.98727, NA, NA, NA, -55.19581, NA, NA, NA, NA, NA, -30.08524, 36.22033))


ggplot(final.df, aes(x = acz, y = coef)) + geom_bar(stat = "identity")

然后我想在x轴上显示当前的所有标签 仅针对选定的几个显示。

1 个答案:

答案 0 :(得分:2)

要填写acz的缺失范围,可以使用complete中的full_seqtidyr函数。默认情况下,他们还将NA放在其他列。

library(ggplot2)
library(tidyr)
# Using OPs data
ggplot(complete(df, acz = full_seq(acz, 1)), 
       aes(factor(acz), coef)) + 
    geom_bar(stat = "identity")  

enter image description here


另一种解决方案是通过传递范围限制将x轴标签直接转换为离散比例:

ggplot(df, aes(acz, coef)) + 
    geom_bar(stat = "identity") +
    scale_x_discrete(limits = seq(min(df$acz), max(df$acz)))