我有类似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 %
?
答案 0 :(得分:9)
使用percent_format
包中的scales
将accuracy
设置为2。
library(ggplot2)
library(scales)
ggplot(df_Filtered, aes(x = Product, y = Relative_Value, fill = Product)) +
scale_y_continuous(labels = percent_format(accuracy = 2)) +
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)
答案 1 :(得分: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)), "%"))
。