如何将 ggplot2 中条形图中 y 轴的比例更改为数千?

How can I change the scale of the y axis in a barplot in ggplot2 to thousands?

我正在使用此代码:

ggplot2::ggplot(DATAFRAME, aes(x = as.factor(VARIABLE))) + ggplot2::geom_bar()

绘制数据框DATAFRAME中变量VARIABLE的每一层出现的次数。但是,这是一个相当长的数据框,所以我想以千为单位而不是单位。有人知道怎么做吗?

您可以使用自定义函数作为 labels 的格式化程序。只需将其添加到您的情节中

+ scale_y_continuous(name = "Count (thousands)",
    labels = function(y) y / 1000)

对于可重现的示例:

ggplot(data.frame(x = 1:2, y = 3:4 * 1000)) + 
    geom_point(aes(x, y)) +
    scale_y_continuous(
        name = "Axis in thousands",
        labels = function(x) x / 1000
)

如果你想花哨一点,你甚至可以将 "k" 粘贴到数字的末尾:

labels = function(x) paste0(x / 1000, "k")