有没有办法在ggplot中将x轴设置为最小值和最大值?

Is there a way to set the x-axis to min and max value in ggplot?

数据:

Month<-c(jan,feb,mar,apr,may)
Values(10,5,8,12,4)

我想知道是否有一种方法可以在不对它进行硬编码的情况下将 x 轴设置为最小值和最大值。例如,除了硬编码 coord_cartesian(ylim = c(4, 12)) 之外,还有一种方法可以将 y 轴分配给最大值和最小值,这样图形会自动将限制设置为 4 和 12。

我们可以从 'Values' 列中提取 range

library(ggplot2)
ggplot(df1, aes(x = Month, y = Values)) + 
     geom_col() + 
     coord_cartesian(ylim = range(df1$Values))

-输出


如果我们需要更改刻度线,请使用 scale_y_continuous

rng_values <- range(df1$Values) -  c(2, 0)
ggplot(df1, aes(x = Month, y = Values)) + 
     geom_col() + 
     coord_cartesian(ylim = rng_values ) + 
     scale_y_continuous(breaks = do.call(seq, 
        c(as.list(rng_values),
            list(by = 0.5))))

数据

df1 <- data.frame(Month = month.abb[1:5], Values = c(10, 5, 8, 12, 4))