简体   繁体   English

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

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

Data:数据:

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

I was wondering if there is a way to set the x axis to min and max values without hardcoding it.我想知道是否有一种方法可以将 x 轴设置为最小值和最大值,而无需对其进行硬编码。 For example instead of hard coding coord_cartesian(ylim = c(4, 12)) is there a way to just assign y axis to max and min so the graph automatically sets the limits at 4 and 12.例如,除了硬编码 coord_cartesian(ylim = c(4, 12)) 之外,还有一种方法可以将 y 轴分配给 max 和 min,以便图形自动将限制设置为 4 和 12。

We can extract the range from the 'Values' column我们可以从“值”列中提取range

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

-output -输出

在此处输入图像描述


If we need to change the tick marks, use scale_y_continuous如果我们需要更改刻度线,请使用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))))

data数据

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

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

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