在ggplot2 2.2.0版中,例如:
tmp_df <- data.frame(x = 1:3, y = 1:3, alpha = rep(0.5, 3)) # x y alpha # 1 1 1 0.5 # 2 2 2 0.5 # 3 3 3 0.5 ggplot(tmp_df, aes(x, y, alpha = alpha)) + geom_bar(stat = 'identity') + scale_alpha(breaks = c(0.25, 0.5, 1), labels = c('a', 'b', 'c'))产生错误:
Error in f(..., self = self) : Breaks and labels are different lengths手动删除scale_alpha的额外alpha值scale_alpha解决问题,但肯定可以通过ggplot来处理这个问题吗?
In ggplot2 version 2.2.0, E.g.:
tmp_df <- data.frame(x = 1:3, y = 1:3, alpha = rep(0.5, 3)) # x y alpha # 1 1 1 0.5 # 2 2 2 0.5 # 3 3 3 0.5 ggplot(tmp_df, aes(x, y, alpha = alpha)) + geom_bar(stat = 'identity') + scale_alpha(breaks = c(0.25, 0.5, 1), labels = c('a', 'b', 'c'))Produces the error:
Error in f(..., self = self) : Breaks and labels are different lengthsManually removing the extra alpha values in scale_alpha fixes the problem, but surely this can be handled some how by ggplot?
最满意答案
您必须提供比例限制,因为tmp_df$alpha始终相同,并且ggplot不知道比例的“范围”。
library(ggplot2) tmp_df <- data.frame(x = 1:3, y = 1:3, alpha = rep(0.5, 3)) tmp_df #> x y alpha #> 1 1 1 0.5 #> 2 2 2 0.5 #> 3 3 3 0.5 ggplot(tmp_df, aes(x, y, alpha = alpha)) + geom_bar(stat = 'identity') + scale_alpha(breaks = c(0.25, 0.5, 1), labels = c('a', 'b', 'c'), limits = c(0, 1))如果alpha维度本身具有范围,则不再需要限制,但请注意,在下面的示例中,将忽略第一个break ,因为它超出范围。 如果你想包括它,那么再次需要limits 。
tmp_df <- data.frame(x = 1:3, y = 1:3, alpha = seq(.5, 1.5, .5)) tmp_df #> x y alpha #> 1 1 1 0.5 #> 2 2 2 1.0 #> 3 3 3 1.5 ggplot(tmp_df, aes(x, y, alpha = alpha)) + geom_bar(stat = 'identity') + scale_alpha(breaks = c(0.25, 0.5, 1), labels = c('a', 'b', 'c'))You must supply the limits for the scale because tmp_df$alpha is always the same, and ggplot does not know the 'range' of the scale.
library(ggplot2) tmp_df <- data.frame(x = 1:3, y = 1:3, alpha = rep(0.5, 3)) tmp_df #> x y alpha #> 1 1 1 0.5 #> 2 2 2 0.5 #> 3 3 3 0.5 ggplot(tmp_df, aes(x, y, alpha = alpha)) + geom_bar(stat = 'identity') + scale_alpha(breaks = c(0.25, 0.5, 1), labels = c('a', 'b', 'c'), limits = c(0, 1))If the alpha dimension has a range itself, limits are no longer necessary, but note the in the following example the first break is ignored, as it is outside the range. limits would again be necessary if you want to include it.
tmp_df <- data.frame(x = 1:3, y = 1:3, alpha = seq(.5, 1.5, .5)) tmp_df #> x y alpha #> 1 1 1 0.5 #> 2 2 2 1.0 #> 3 3 3 1.5 ggplot(tmp_df, aes(x, y, alpha = alpha)) + geom_bar(stat = 'identity') + scale_alpha(breaks = c(0.25, 0.5, 1), labels = c('a', 'b', 'c'))
更多推荐
发布评论