在scale_x_log10百分比标签(Percent labels in scale_x_log1

2019-10-22 04:23发布

我试图绘制使用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)

从鳞包,我的轴有标签:

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

注意重复“0%”。 我不解,这很可能与鳞%的函数来完成,给出

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

努力没有四舍五入的代码我的“自己”的功能:

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%.....

但我似乎无法复制此。 什么是这样做的正确方法?

Answer 1:

Replace

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

with

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

The problem is that comma considers its whole input to determine a commonly usable number of significant digits – but this is precisely what you do not want. Unfortunately the function documentation fails to mention this. The relevant section can instead be found in format, which comma calls:

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



文章来源: Percent labels in scale_x_log10
标签: r ggplot2