scale_x_log10 中的百分比标签

Percent labels in scale_x_log10

我正在尝试使用 ggplot 在 R 中绘制密度图。一个细微差别是我的 x 轴是对数的,使用 scale_x 连续。以下代码运行良好:

ggplot(MELTCOMP,aes(x=value)) + geom_density(aes(fill=variable), alpha = 0.1) + 
                            scale_fill_manual(
                                              name = "Spend", 
                                              values = c("blue","red","green"), 
                                              labels = c("A","B","C")
                                              ) +
                            scale_x_log10(breaks = c(0.00001,0.0001,0.001,0.01,0.1,1,10,100),labels = percent) +
                            geom_vline(aes(xintercept = c(0.00001,0.0001,0.001,0.01,0.1,1,10,100)), color = "grey") + 
                            theme(axis.ticks = element_blank(), panel.background = element_blank(), panel.grid = element_blank(),
                                  axis.text.y = element_blank())

问题在于 x 轴的显示方式。当我使用:

 scale_x_log10(breaks = c(0.00001,0.0001,0.001,0.01,0.1,1,10,100),label = percent)

从 scales 包中,我的轴有标签:

0% - 0% - 0% - 0% - 10% - 100% - ...

注意重复的“0%”。我很困惑,这可能与比例百分比函数有关,给出为

function (x) 
{
x <- round_any(x, precision(x)/100)
paste0(comma(x * 100), "%")
}

尝试在没有舍入的情况下编写我的 "own" 函数:

NRPercent <- function(x) {
    paste0(comma(x * 100), "%")
}

scale_x_log10(breaks = c(0.00001,0.0001,0.001,0.01,0.1,1,10,100),label = NRpercent)

给出:

0.001% - 0.010% - 0.100% - 1.000% - 10.000% - ...

现在我强制每个数字保留三位小数,这通常会导致重叠。我想要的是:

0.001% - 0.01% - 0.1% - 1% - 10% - 100% - 1000% .....

但我似乎无法复制它。正确的做法是什么?

替换

paste0(comma(x * 100), "%")

paste0(sapply(x * 100, comma), "%")

问题在于 comma 考虑其 整个 输入来确定有效数字的常用数量 – 但这正是您所做的 想要。不幸的是,函数文档没有提到这一点。相关部分可以在 format 中找到,comma 调用:

Numeric vectors are encoded with the minimum number of decimal places needed to display all the elements to at least the ‘digits’ significant digits.