去除 ggplot2 中的 y 轴小数

11

我有像这样的数据,df_Filtered

Product Relative_Value
Car     0.12651458
Plane   0.08888552
Tank    0.03546231
Bike    0.06711630
Train   0.06382191

我想用GGplot2制作数据的条形图:

ggplot(df_Filtered, aes(x = Product, y = Relative_Value, fill = Product)) +
    scale_y_continuous(labels = scales::percent) +
    geom_bar(stat = "identity") +
    theme_bw() +
    theme(plot.background = element_rect(colour = "black", size = 1)) +
    theme(legend.position = "none") +
    theme(plot.title = element_text(hjust = 0.5))
    labs(x ="Product", y = "Percentage of total sell", title = "Japan 2010") +
    theme(panel.grid.major = element_blank())

如何在图表的y轴上去掉小数点?这样它会显示20 %而不是20.0 %


1
一种选择是手动创建断点和标签。使用 scale_y_continuous(breaks = seq(0,1,0.05), labels = paste0(seq(0,1,0.05)*100," %")) 代替。 - AntoniosK
那将是一个解决方案,问题只是我想用不同的比例在“相对值”上制作40个条形图。 - KGB91
我以为你的 y 轴上始终会是一个百分比值。这将包括从 0% 到 100% 的所有内容。 - AntoniosK
1
你说得对!太好了,它解决了我的问题!非常感谢。 - KGB91
1
只有在ylim函数中使用了(固定)值,才会出现您描述的问题,因为这会固定y轴范围。 - AntoniosK
显示剩余2条评论
2个回答

25

使用scales包中的percent_format函数来将accuracy设置为1。

library(ggplot2)
library(scales)

ggplot(df_Filtered, aes(x = Product, y = Relative_Value, fill = Product)) +
  scale_y_continuous(labels = percent_format(accuracy = 1)) +
  geom_bar(stat = "identity") +
  theme_bw() +
  theme(plot.background = element_rect(colour = "black", size = 1)) +
  theme(legend.position = "none") +
  theme(plot.title = element_text(hjust = 0.5)) +
labs(x ="Product", y = "Percentage of total sell", title = "Japan 2010") +
  theme(panel.grid.major = element_blank()) 

输入图像描述

数据

df_Filtered <- read.table(text = "Product Relative_Value
Car     0.12651458
                 Plane   0.08888552
                 Tank    0.03546231
                 Bike    0.06711630
                 Train   0.06382191",
                 header = TRUE, stringsAsFactors = FALSE)

3
刚刚在检查这个! :) 有趣的是,percent_format(1) 在y轴上显示5%而不是4%。 - AntoniosK
1
@AntoniosK 有趣,我认为 percent_format(1) 应该和 percent 相同,但它们并不相同。 - www
谢谢!那个很好用,除了一个问题,就是我得到的是4%而不是5%,正如@AntoniosK所指出的那样。 - KGB91
format_percent 函数中: "Accuracy: A number to round to. Use (e.g.) 0.01 to show 2 decimal places of precision." 大多数情况下,您将希望使用1。 - stevec
@www 如果你同意的话,最好更新你的答案为 accuracy = 1,因为这一点并不显然(我以为它会像 round() 一样工作,所以我第一次尝试使用 accuracy = 0 来获取整数百分比,但是那返回了NA)。 - stevec
1
@stevec 感谢您关注此事并提出建议。我已将我的帖子更新为 accuracy = 1 - www

1

scales::percent_format(accuracy = 2) 不允许手动设置 breaks = c(0, 0.5, .10)。 因此,我必须创建手动函数 scale_y_continuous(breaks = c(0, 0.5, .10), labels = function(x) paste0(round(as.numeric(x*100)), "%"))


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接