Is there a way of manipulating ggplot scale breaks and labels?
但是,我发现在具有许多方面和可能是
1 2 3 4 5 6 7 8 9 | df <- data.frame( fac=rep(LETTERS[1:10], 100), x=rnorm(1000) ) ggplot(df, aes(x=x)) + geom_bar(binwidth=0.5) + facet_grid(~fac) + scale_x_continuous(formatter="percent") |
我知道我可以通过向
提供
但是,我正在处理包含许多问题和十几个交叉中断的调查数据,因此需要找到一种自动执行此操作的方法。
有没有办法告诉
编辑:理想情况下,我不想指定最小和最大点,而是以某种方式利用内置的 ggplot 刻度训练,并使用默认计算的刻度限制。
您可以在调用 ggplot 时传入诸如
1 2 3 4 5 6 | ggplot(df, aes(x=x)) + geom_bar(binwidth=0.5) + facet_grid(~fac) + scale_x_continuous(breaks = c(min(df$x), 0, max(df$x)) , labels = c(paste( 100 * round(min(df$x),2),"%", sep =""), paste(0,"%", sep =""), paste( 100 * round(max(df$x),2),"%", sep ="")) ) |
或使用
更新
在最新版本的 ggplot2 中,
1 2 3 4 5 6 7 8 9 10 11 | myBreaks <- function(x){ breaks <- c(min(x),median(x),max(x)) names(breaks) <- attr(breaks,"labels") breaks } ggplot(df, aes(x=x)) + geom_bar(binwidth=0.5) + facet_grid(~fac) + scale_x_continuous(breaks = myBreaks,labels = percent_format()) + opts(axis.text.x = theme_text(angle = 90, hjust = 1,size = 5)) |
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | library(ggplot2) # Compute the list of breaks using original_func, # then remove any of these that occur in remove_list remove_breaks <- function(original_func, remove_list = list()) { function(x) { original_result <- original_func(x) original_result[!(original_result %in% remove_list)] } } # Compute the list of labels using original_func, # then remove any of these that occur in remove_list remove_labels <- function(original_func, remove_list = list()) { function(x) { original_result <- original_func(x) replace(original_result, original_result %in% remove_list, '') } } # Original plot ggplot(data.frame(x=c(1,2,3,4,5,6,7,8), y = c(1,4,9,16,25,36,49,64))) + geom_line(aes(x, y)) + scale_x_continuous(breaks = scales::breaks_pretty(9), minor_breaks = scales::breaks_pretty(18), labels = scales::label_number_auto()) + scale_y_continuous(breaks = scales::breaks_pretty(9), minor_breaks = scales::breaks_pretty(18), labels = scales::label_number_auto()) # Remove some breaks from the x-axis, and remove some labels from the y-axis ggplot(data.frame(x=c(1,2,3,4,5,6,7,8), y = c(1,4,9,16,25,36,49,64))) + geom_line(aes(x, y)) + scale_x_continuous(breaks = remove_breaks(scales::breaks_pretty(9), seq(3,6)), minor_breaks = remove_breaks(scales::breaks_pretty(18), seq(3,6,0.5)), labels = scales::label_number_auto()) + scale_y_continuous(breaks = scales::breaks_pretty(9), minor_breaks = scales::breaks_pretty(18), labels = remove_labels(scales::label_number_auto(), seq(20, 30))) |
当然,使用我简单的