我计算了以下数据,以便将标签绘制到我在 R 中的堆叠条形图上:
Scenario Losses Model percent
1 Scenario 1 23221 Upstream 0.6095231
2 Scenario 1 14876 Downstream 0.3904769
3 Scenario 2 722 Upstream 0.3764338
4 Scenario 2 1196 Downstream 0.6235662
5 Scenario 3 28487 Upstream 0.7256355
6 Scenario 3 10771 Downstream 0.2743645
当我绘制这个时:
ggplot(test, aes(x = Scenario, y = percent, fill = Model, label = paste(percent * 100, "%", sep = ""))) +
geom_bar(stat = "identity", position = "fill", color = "black", alpha=0.8)+
theme_bw()+
scale_fill_manual(values = c("#00008B", "#800080"))+
geom_text(position = position_stack(vjust = 0.5), size = 2)
结果图为:
这个问题的解决方案已经在网上广泛讨论。通过添加以下代码,应该减少逗号的数量:
scale_y_continuous(label = scales::percent(percent, accuracy=0.1))
我已经尝试了很多解决方法,但每次我都以:
Error in number(x = x, accuracy = accuracy, scale = scale, prefix = prefix, :
object 'percent' not found
我真的无法想象我需要什么机会,因为我准确地看到这个代码块在另一个线程上成功运行。
任何帮助表示赞赏。
你可以使用
round
到你的 label
例如只显示两个 digits
这样的:
library(ggplot2)
ggplot(test, aes(x = Scenario, y = percent, fill = Model, label = paste(round(percent * 100, 2), "%", sep = ""))) +
geom_bar(stat = "identity", position = "fill", color = "black", alpha=0.8)+
theme_bw()+
scale_fill_manual(values = c("#00008B", "#800080"))+
geom_text(position = position_stack(vjust = 0.5), size = 2)
创建于 2023-03-31 与 reprex v2.0.2
使用的数据:
test = read.table(text = " Scenario Losses Model percent
1 Scenario_1 23221 Upstream 0.6095231
2 Scenario_1 14876 Downstream 0.3904769
3 Scenario_2 722 Upstream 0.3764338
4 Scenario_2 1196 Downstream 0.6235662
5 Scenario_3 28487 Upstream 0.7256355
6 Scenario_3 10771 Downstream 0.2743645", header = TRUE)
而不是使用
paste
,使用sprintf
如下所示:
label = sprintf("%.2f%%",percent * 100)
即
ggplot(test, aes(x = Scenario, y = percent, fill = Model,
label = sprintf("%.2f%%",percent * 100))) +
geom_bar(stat = "identity", position = "fill", color = "black", alpha=0.8)+
theme_bw()+
scale_fill_manual(values = c("#00008B", "#800080"))+
geom_text(position = position_stack(vjust = 0.5), size = 2)
还有另一种方法是对文本标签和轴标签使用
scales::percent
,如下所示:
注意:不要脸偷了@Quinten的数据
library(ggplot2)
ggplot(test, aes(x = Scenario, y = percent, fill = Model, label = scales::percent(percent))) +
geom_bar(stat = "identity", position = "fill", color = "black", alpha = 0.8) +
theme_bw() +
scale_fill_manual(values = c("#00008B", "#800080")) +
scale_y_continuous(labels = scales::percent) +
geom_text(position = position_stack(vjust = 0.5))