我有这样的数据
df<- structure(list(process = structure(16:1, .Label = c("A", "AA",
"AAA", "AAAA", "AAAAA", "B", "BB", "BBB", "BBBB", "BBBBB", "BBBBBB",
"C", "CC", "CCC", "CCCC", "CCCCC"), class = "factor"), percentage = c(1.869158879,
0.934579439, 5.046728972, 1.682242991, 0.747663551, 15.70093458,
1.869158879, 3.551401869, 3.738317757, 0.373831776, 2.61682243,
1.121495327, 13.45794393, 21.30841121, 14.76635514, 11.21495327
), lab.ypos = c(0.9345794395, 2.3364485985, 5.327102804, 8.6915887855,
9.9065420565, 18.130841122, 26.9158878515, 29.6261682255, 33.2710280385,
35.327102805, 36.822429908, 38.6915887865, 45.981308415, 63.364485985,
81.40186916, 94.392523365)), class = "data.frame", row.names = c(NA,
-16L))
我将其绘制如下所示
ggplot(df, aes(x="", y=percentage, fill=process))+
geom_bar(stat="identity", width=1)+
coord_polar("y", start=0)+
geom_text(aes(y = lab.ypos, label = round(percentage)), color = "white")
我基本上想将数字显示为粗体并带有%符号 有没有办法做到这一点?
答案 0 :(得分:0)
您可以使用adorn_pct_formatting()
包中的janitor
函数将值格式化为百分比。该函数将更改每个数字列,因此您需要在应用adorn_pct_formatting()
之前隔离百分比列。它还会将您的值乘以100,因此您还需要先将其除以删除格式。我建议创建一个新的变量,该变量的格式应专门设置为绘图中的标签。
# library tidyverse
# library janitor
df <- df %>% # overwrites your original data object
mutate(label = percentage/100) %>% # creates the label column
select(process, label) %>% # isolates the label column for percent formatting
adorn_pct_formatting() %>% # applies the formatting to your numeric columns
bind_cols(list(lab.ypos = df$lab.ypos, # appends your other numeric columns
percentage = df$percentage))
head(df)
process label lab.ypos percentage
1 CCCCC 1.9% 0.9345794 1.8691589
2 CCCC 0.9% 2.3364486 0.9345794
3 CCC 5.0% 5.3271028 5.0467290
4 CC 1.7% 8.6915888 1.6822430
5 C 0.7% 9.9065421 0.7476636
6 BBBBBB 15.7% 18.1308411 15.7009346
您可以看到现在有了一个新列,该列专门格式化为绘图的标签。现在,您可以运行原始的ggplot
代码,而只需按以下方式替换label参数:
ggplot(df, aes(x="", y=percentage, fill=process))+
geom_bar(stat="identity", width=1)+
coord_polar("y", start=0)+
geom_text(aes(y = lab.ypos, label = label), color = "white")
对于标签放置,没有简单的方法可以动态地自动避开位置而不加载另一个包装。我建议使用geom_label_repel()
软件包中的ggrepel
函数,而不要使用geom_text()
。
library(ggrepel)
ggplot(df, aes(x="", y=percentage, fill=process))+
geom_bar(stat="identity", width=1)+
coord_polar("y", start=0)+
geom_label_repel(aes(label = label, y = lab.ypos), nudge_x = .5)
没有nudge_x
参数,标签将保留在饼图的范围内。您可以更改nudge_x
的值,以更改标签在图表外的“轻推”距离。