如何将图例值显示为百分比

时间:2019-12-04 13:38:21

标签: r ggplot2

对于以下数据:

   RW GA Freq   percFreq
    0  0    9 0.13043478
    0  3    1 0.01449275
    0 14    1 0.01449275
    0 16    1 0.01449275
    0 23    1 0.01449275
    0 25    1 0.01449275
    0 29    2 0.02898551
    0 30    1 0.01449275
    2 30    1 0.01449275
   15 30    2 0.02898551
   19 30    1 0.01449275
   22 30    1 0.01449275
   24 30    1 0.01449275
   29 30    1 0.01449275
   30 29   16 0.23188406
   30 30   29 0.42028986

我想将以下图中的图例值更改为百分比:

enter image description here

生成图的脚本是:

ggplot(counts, aes(x=RW, y=GA, size=Freq, color=as.factor(percFreq))) + geom_point(alpha=0.7) +
    scale_size(range = c(1, 10), name="Freq", limits=c(1,30), breaks=lbreaks) +
    scale_color_discrete(name="Freq", breaks=lbreaks)

基本上,我不想在图例中显示0.42028986,而是希望将其显示为42%。

我该怎么做?

2 个答案:

答案 0 :(得分:3)

使用“比例”库中的“百分比”。

加载scales库:

library(scales)

然后将labels = percent添加到您的离散比例中:

ggplot(counts, aes(x=RW, y=GA, size=Freq, color=as.factor(percFreq))) + 
  geom_point(alpha=0.7) +
  scale_size(range = c(1, 10), name="Freq", limits=c(1,30), breaks=lbreaks) +
  scale_color_discrete(name="Freq", breaks=lbreaks, labels = percent(lbreaks, accuracy = .01))

如果要更改数字舍入的方式,请使用accuracy参数:

scales::percent(percFreq, accuracy = .001)

enter image description here

(具有accuracy = .1

希望这会有所帮助。

答案 1 :(得分:2)

您可以将percFreq转换为百分比

df$percFreq <- df$percFreq*100 

或者您可以color=as.factor(percFreq*100)))

----可复制的示例

df <- data.frame(RW = round(runif(16,0,30)),
                 GA=round(runif(16,0,30)),
                 Freq=round(runif(16,1,30)),
                 percFreq = runif(16,0.1,0.9))
df$percFreq <- round(df$percFreq*100,digits = 2)

ggplot(df, aes(x=RW, y=GA, size=Freq, color=as.factor(percFreq))) +
       geom_point(alpha=0.7) + 
       scale_size(range = c(1, 10), name="Freq", limits=c(1,30)) +
       scale_color_discrete(name="%")

我建议您不要这样做,但是如果您想用数字来%,只需paste(df$percFreq,"%",sep=" ")

enter image description here

相关问题