在 R 中更改饼图中切片的顺序

Changing the order of the slices in a pie chart in R

我正在尝试更改R中饼图中切片的顺序。我想要0度右侧的最大值(38,属于农业集约化),第二大切片(20,属于森林砍伐)在左边,第三大值(17,城市化)在右边第二个,最低值(10,湿地或河流改造)在左边第二个。 我使用了下面写的代码。非常感谢你帮助我!

亲切的问候,

孙燕姿

饼图

df <- data.frame(value = c(38, 20, 17, 10),
                 group = c('Agricultural intensification', 'Deforestation', 'Urbanization', 'Wetland or river modification'))

library(ggplot2)

ggplot(df, aes(x = "", y = value, fill = group)) + 
  labs(x='Taxon order', y='Driver', title='Driver per taxon order') + theme(plot.title = element_text(hjust = 0.5, size=20, face='bold')) +
  geom_col(color = "black") +
  coord_polar("y", start=0) +
  geom_text(aes(label = paste0(slices, "%")), position = position_stack(vjust=0.5)) +
  labs(x = NULL, y = NULL, fill = NULL) + theme(axis.line = element_line(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), panel.background = element_blank()) +
  theme_void() +
  scale_fill_viridis_d() 

将您的 group 列转换为 factor 并按照您想要的顺序设置 levels

df <- data.frame(
  value = c(38, 20, 17, 10),
  group = c("Agricultural intensification", "Deforestation", "Urbanization", "Wetland or river modification")
)

library(ggplot2)

df$group <- factor(df$group, levels = rev(c("Agricultural intensification", "Urbanization", 
                                        "Wetland or river modification", "Deforestation")))

ggplot(df, aes(x = "", y = value, fill = group)) +
  labs(x = "Taxon order", y = "Driver", title = "Driver per taxon order") +
  theme(plot.title = element_text(hjust = 0.5, size = 20, face = "bold")) +
  geom_col(color = "black") +
  coord_polar("y", start = 0) +
  geom_text(aes(label = paste0(value, "%")), position = position_stack(vjust = 0.5)) +
  labs(x = NULL, y = NULL, fill = NULL) +
  theme(axis.line = element_line(), panel.grid.major = element_blank(), panel.grid.minor = element_blank(), panel.border = element_blank(), panel.background = element_blank()) +
  theme_void() +
  scale_fill_viridis_d()