[英]How to change ggplot2 x-axis values in barplot?
I would like to make a barplot in R, where the last bar in the graph indicates that last is the sum of all values whose the frequency is greater than a certain threshold. 我想在R中制作一个条形图,其中图中的最后一个条形表示最后一个是频率大于某个阈值的所有值的总和。 I want to represent this information on x-value correspondent to the last bar.
我想在最后一个栏上代表x值的相关信息。 For instance:
例如:
library(ggplot2)
x <- c(1, 2, 3, 4, 5)
y <- c(4000, 3000, 2000, 1000, 500)
df <- data.frame(x, y)
names(df) <- c("Var1", "Freq")
theme_set(theme_classic())
g <- ggplot(df, aes(Var1, Freq))
g + geom_bar(stat = "identity", width = 0.5, fill = 'tomato2') +
xlab('Var1') +
ylab('Freq') +
theme(axis.text.x = element_text(angle = 0,
vjust = 0.6,
colour = "black"),
axis.text.y = element_text(colour = "black"))
The above code produces a chart similar to this: 上面的代码生成了一个类似于下面的图表:
But on the last bar, I want that last value of x-axis ( x = 5
) be displayed as >= 5
. 但是在最后一个栏上,我希望x轴(
x = 5
)的最后一个值显示为>= 5
。
So far, I've tried to use scale_x_discrete
. 到目前为止,我已经尝试使用
scale_x_discrete
。 So I added to the above code the following lines: 所以我在上面的代码中添加了以下几行:
n <- 5
# I'm not very creative with names.
.foo <- function(x, n) {
if (x == n) {
element <- paste('\u2265', toString(x), sep = ' ')
} else {
element <- toString(x)
}
}
labels <- sapply(seq(n), .foo, n)
g + scale_x_discrete(breaks = sapply(seq(n), function(x) toString(x)),
labels = labels)
This code formats the x-axis as I wish but it overrides the barplot, leaving an empty chart: 这段代码按照我的意愿格式化x轴,但它会覆盖条形图,留下一个空图表:
How can I do this? 我怎样才能做到这一点?
One approach would be to avoid changing the axis tick labels directly, but convert your categorical data in Var1
to a factor, then relevel that factor using forcats::fct_lump
such that the final factor is ≥5
一种方法是避免直接更改轴刻度标签,但将
Var1
中的分类数据转换为因子,然后使用forcats::fct_lump
将该因子重新调整,使最终因子≥5
# Insert after df generated, before plot call
library(forcats)
df <- df %>%
mutate(Var1 = as_factor(Var1),
Var1 = fct_lump_min(Var1, min = 501, w = Freq, other_level = "≥5"))
The problem was that, as pointed out by @Z.Lin comment, I was assign the geom_bar(...)
to the ggplot object before using scale_x_discret
. 问题是,正如@ Z.Lin评论所指出的那样,我在使用
scale_x_discret
之前将geom_bar(...)
分配给ggplot对象。 Here is the solution: 这是解决方案:
library(ggplot2)
...
labels <- sapply(seq(n), .foo, n)
g <- ggplot(df, aes(Var1, Freq)) +
scale_x_discrete(breaks = sapply(seq(n), function(x) toString(x)),
labels = labels)
g + geom_bar(stat = "identity", width = 0.5, fill = color) +
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.