如何在R中对ggplot中使用的数字进行四舍五入



首先是示例数据和操作,然后是我用来创建水平条形图的代码。一切都很好,只是我不知道如何对数据标签中使用的数字进行四舍五入。首先,如何对数据标签中的数字进行四舍五入。我用了下面的";scale_y_continuous(labels=scales::逗号,精度=1(";并将其附加到我所拥有的内容中,但由于准确性旁边的逗号而出现错误。此外,在数据帧中尝试了一个mutate(和round命令(,但没有成功。关于如何最好地实现这一点,有什么想法吗?

A<- c(150.333,125.888,0,-300.5555,-350.444,-370.99999)
Series<- c("Construction","Manufacturing","Information","Health_Care","Education","Government")
testdf <- data.frame(A,Series)
ggplot(data = testdf, aes(y = A, x = reorder(Series, A))) +
geom_col(color = "blue") +
coord_flip() +
scale_y_continuous(expand = expansion(mult = 0.5)) +
geom_text(aes(label = A, hjust = ifelse(A > 0, 0, 1), y = A + ifelse(A > 0, 10, -10))) +
labs(x = NULL) +
ggtitle("Job Growth") +
theme(
plot.title.position = "plot",
plot.title = element_text(hjust = 0.5)
)

我也试过这个。没有错误,但绘图没有改变。

jobgrowth<- ggplot(data = testdf, aes(y = A, x = reorder(Series, A))) +
geom_col(color = "blue") +
coord_flip() +
scale_y_continuous(label = scales::comma(A, accuracy=1),expand = 
expansion(mult = 0.5)) +
geom_text(aes(label = A, hjust = ifelse(A > 0, 0, 1), y = A + ifelse(A > 0, 
10, -10))) +
labs(x = NULL) +
ggtitle("Job Growth") +
theme(
plot.title.position = "plot",
plot.title = element_text(hjust = 0.5)
)

与所有概念或软件包的新手一样,你会陷入兔子洞。这不起作用,所以你试试这个,试试那个。随着时间的推移,与核心概念问题的偏离越来越远(https://datavizpyr.com/how-to-add-labels-over-each-bar-in-barplot-in-r/)。问题不在于scale_y_continuous,而在于geom_text项。这似乎是一个无聊的时刻,但过了一段时间,我注意到底部的刻度在变化,但数据标签没有变化,因此它必须是其他东西。

jobgrowth<- ggplot(data = testdf, aes(y = A, x = reorder(Series, A))) +
geom_col(color = "blue") +
coord_flip() +
scale_y_continuous(labels = label_comma() ,expand = expansion(mult = 0.5)) +
geom_text(aes(label = round(A,0), hjust = ifelse(A > 0, 0, 1), y = A + ifelse(A > 0, 
10, -10))) +
labs(x = NULL) +
ggtitle("Job Growth") +
theme(
plot.title.position = "plot",
plot.title = element_text(hjust = 0.5)
)

最新更新